RemoveDuplicates

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

           

Description

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

Details

Double click on the code to select all.

 

;