Matt
Matt

Reputation: 26971

Actual difference between two lists - not Except

Let's say I have the list

var L1 = new List<int>{1,1,2};
var L2 = new List<int>{1};

If I do

L1.Except(L2)

I get List<int>{2} - Fair enough.

But is there shorthand to do something like L1.Minus(L2) where I would get List<int>{1,2}

Basically only remove items as many times as it finds them in L2.

I could write this out - hoping I don't have to.

Upvotes: 1

Views: 89

Answers (2)

dodgy_coder
dodgy_coder

Reputation: 13033

Minimal example using ForEach and a lambda expression:

L2.ForEach(x => L1.Remove(x));

Upvotes: 2

John Wu
John Wu

Reputation: 52240

If you were to write it yourself, it could look like this:

public static class ExtensionMethods
{
    static public IEnumerable<T> Minus<T>(this IEnumerable<T> input, IEnumerable<T> removal)
    {
        var result = input.ToList();
        foreach (var r in removal) result.Remove(r);
        return result;
    }
}

Or possibly like this if you aren't so worried about readability:

public static class ExtensionMethods
{
    static public IEnumerable<T> Minus<T>(this IEnumerable<T> input, IEnumerable<T> removal)
    {
        var remaining = removal.ToList();
        return input.Where
        (
            a => !remaining.Remove(a)
        );      
    }
}

Example usage:

public class Program
{
    public static void Main()
    {
        var L1 = new List<int>{1,1,2};
        var L2 = new List<int>{1};
        var L3 = L1.Minus(L2);


        foreach (var l in L3)
        {
            Console.WriteLine(l);
        }
    }
}

Output:

1
2

Working example on DotNetFiddle

Upvotes: 3

Related Questions