0

I have objects which contain a dictionary and a name (string). I want to loop through these objects, compare their dictionaries and names, and if any dictionaries & names are exact matches, I want to remove all duplicates, then return a list of objects where none of the dictionaries & names match.

Here is what I have so far:

private void removeDuplicates(List<MyObject> objectList)
{
    List<Dictionary<string,string>> listOfObjDicts = new List<Dictionary<string,string>>();
    List<string> nameList = new List<string>();

     foreach(MyObject object in objectList)
     {
         nameList.Add(MyObject.name);
         listOfObjDicts.Add(MyObject.dict);
     }
     //compare name & dictionary against all other objects, then remove any duplicates from objectList.
}

It is probably safe to assume that even this structure of a foreach loop iterating over the list of objects isn't great - because I want to return a list of objects, not a list of names and a list of dictionaries. I'm pretty stuck on this. Some people have mentioned LINQ, but I really have no experience or ability to read/understand LINQ syntax.

Christopher
  • 790
  • 12
  • 30
  • 1
    You could use `objectList.Distinct()` with a custom comparer. – itsme86 Mar 13 '18 at 20:21
  • @MikeMcCaughan thank you, yes after reviewing that question I think this is a duplicate. I had not seen that yet. Again, thank you :) – Christopher Mar 13 '18 at 20:22
  • `Some people have mentioned LINQ` Linq is not a magic tool. You can implement all of its logic by ordinary loops. So if you can't read/understand it, use classical loops – Eser Mar 13 '18 at 20:26
  • @Eser You lie! LINQ is nothing short of incomprehensible magic. But honestly I would prefer the classical looping but I can't seem to pull together the logical blueprint for it. – Christopher Mar 13 '18 at 20:33
  • @Christopher `var uniqueList = objectList.GroupBy(x=>x.name).Select(x=>x.First()).ToList();` – Eser Mar 13 '18 at 20:42
  • @Eser That would return all the objects with distinct names. But what I want is all objects with distinct name && dictionary. – Christopher Mar 14 '18 at 12:22

0 Answers0