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

RemoveDuplicates

Removes items from a collection based on the condition you provide. This is useful if a query gives you some duplicates that you can't seem to get rid of. Some Linq2Sql queries are an example of this. Use this method afterward to strip things you know are in the list multiple times

Source

public static IEnumerable<T> RemoveDuplicates<T>(this ICollection<T> list, Func<T, int> Predicate)
{
    var dict = new Dictionary<int, T>();

    foreach (var item in list)
    {
        if (!dict.ContainsKey(Predicate(item)))
        {
            dict.Add(Predicate(item), item);
        }
    }

    return dict.Values.AsEnumerable();
}

Example

var employees = (from x in context.Employees
                 join t in context.PhonesNumbers on x.EmpId equals t.EmpId
                 select new { Employee = x, Phone = t });

//we now have multiple employee records if an employee had more than one phone number

employees = employees.RemoveDuplicates(x => x.EmpId);

Author: Chris Meijers

Submitted on: 25 okt. 2010

Language: C#

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

Views: 6215