ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

With and Without

Fake immutability in an existing list class by adding a "With" and "Without" method

Source

public static class ListExtensions
{
    public static TList With<TList, T>(this TList list, T item) where TList : IList<T>, new()
    {
        TList l = new TList();

        foreach (T i in list)
        {
            l.Add(i);
        }
        l.Add(item);

        return l;
    }

    public static TList Without<TList, T>(this TList list, T item) where TList : IList<T>, new()
    {
        TList l = new TList();

        foreach (T i in list.Where(n => !n.Equals(item)))
        {
            l.Add(i);
        }

        return l;
    }
}

Example

List<int> nums = new List<int>() { 1, 2, 3, 4, 5 };

foreach (int i in nums.With(6))
{
    Console.WriteLine(i);
}

foreach (int i in nums.Without(3))
{
    Console.WriteLine(i);
}

Author: unknown

Submitted on: 8 feb. 2008

Language: C#

Type: System.Collections.Generic.IList<T>

Views: 6507