0

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!

Community
  • 1
  • 1
Exitos
  • 29,230
  • 38
  • 123
  • 178
  • Is it just the string that makes it a duplicate? – Ash Burlaczenko Nov 30 '12 at 16:54
  • sorry Konrad I actually want to use Lamda syntax.... – Exitos Nov 30 '12 at 16:58
  • Yeah, there is a perfect lambda syntax answer in that question - you just gotta look. This is a duplicate question... – Tim Hobbs Nov 30 '12 at 17:00
  • Are you trying to produce the list of removed items in addition to the list without duplicates, or is `dupesAsList` a by-product of your strategy? – Sergey Kalinichenko Nov 30 '12 at 17:31
  • Please look at what im asking and what you have all incorrectly marked as duplicate. How do I remove the dupes that arent of the highest id in the original? hmm, thanks for not giving me the answer and closing my question! – Exitos Dec 03 '12 at 13:22

0 Answers0