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

ExceptWithDuplicates

Returns a List of T except what's in a second list, without doing a distinct

Source

public static List<TSource> ExceptWithDuplicates<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
	{      		
		List<TSource> s1 = second.ToList();	
		List<TSource> ret = new List<TSource>();

        first.ToList().ForEach(n =>
		{
			if (s1.Contains(n))
                s1.Remove(n);
            else
                ret.Add(n);

		});

        return ret;

Example

void Main()
{
       List<int> a = new List<int> {1,8,8,3};
       List<int> b = new List<int> {1,8,3};
       
       var x = a.ExceptWithDuplicates(b); //returns list with a single element: 8
       var y = a.Except(b);       //returns an empty list

}

Author: Avraham Seff

Submitted on: 8 dec 2014

Language: C#

Type: List

Views: 3514