Possible Duplicate:
Remove duplicates in the list using linq
I'm trying to remove duplicates from an IQueryable
collection. I'm thinking that I need to do some sort of nested select but I'm not really sure. I created a script in linqpad that has the original list with duplicate items both expanded and collapsed.
What I want to do is select the items from my listWithDuplicates
that are not in the dupesAsList
. I also want to keep the record with the highest id in the listWithDuplicates
if its found to be duplicating...
Wondered if someone could help or tell me best way to remove duplicates?
void Main()
{
var listWithDuplicates = new List<Tuple<int,string>>();
listWithDuplicates.Add(new Tuple<int,string>(1,"Dog"));
listWithDuplicates.Add(new Tuple<int,string>(2,"Cat"));
listWithDuplicates.Add(new Tuple<int,string>(3,"Dog"));
listWithDuplicates.Add(new Tuple<int,string>(4,"Chicken"));
listWithDuplicates.Add(new Tuple<int,string>(5,"Dog"));
listWithDuplicates.Add(new Tuple<int,string>(6,"Dog"));
listWithDuplicates.Add(new Tuple<int,string>(7,"Chicken"));
var dupesAsList = listWithDuplicates.GroupBy(s => s.Item2).SelectMany(grp => grp.Skip(1));
var dupesGrouped = listWithDuplicates.GroupBy(s => s.Item2).Where(x => x.Count() > 1).Select(x => x.Key);
dupesAsList.Dump();
dupesGrouped.Dump();
}
NOTE : I need to do this with a lambda expression not query syntax!