With and Without

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);
}

Description

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

Details

Double click on the code to select all.

 

;