Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering duplicates out of an IEnumerable

Tags:

I have this code:

class MyObj {     int Id;     string Name;     string Location; }  IEnumerable<MyObj> list; 

I want to convert list to a dictionary like this:

list.ToDictionary(x => x.Name); 

but it tells me I have duplicate keys. How can I keep only the first item for each key?

like image 931
newmem Avatar asked Nov 04 '09 08:11

newmem


People also ask

How do I remove duplicates from multiple columns in R?

distinct() function can be used to filter out the duplicate rows. We just have to pass our R object and the column name as an argument in the distinct() function.

Does Linq Union remove duplicates?

Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found. Union removes duplicates. So this method can be thought of as two actions: it combines the two collections and then uses Distinct() on them, removing duplicate elements.


1 Answers

I suppose the easiest way would be to group by key and take the first element of each group:

list.GroupBy(x => x.name).Select(g => g.First()).ToDictionary(x => x.name); 

Or you could use Distinct if your objects implement IEquatable to compare between themselves by key:

// I'll just randomly call your object Person for this example. class Person : IEquatable<Person>  {     public string Name { get; set; }      public bool Equals(Person other)     {         if (other == null)             return false;          return Name == other.Name;     }      public override bool Equals(object obj)     {         return base.Equals(obj as Person);     }      public override int GetHashCode()     {         return Name.GetHashCode();     } }  ...  list.Distinct().ToDictionary(x => x.Name); 

Or if you don't want to do that (maybe because you normally want to compare for equality in a different way, so Equals is already in use) you could make a custom implementation of IEqualityComparer just for this case:

class PersonComparer : IEqualityComparer<Person> {     public bool Equals(Person x, Person y)     {         if (x == null)             return y == null;          if (y == null)             return false;          return x.Name == y.Name;     }      public int GetHashCode(Person obj)     {         return obj.Name.GetHashCode();     } }  ...  list.Distinct(new PersonComparer()).ToDictionary(x => x.Name); 
like image 197
Joren Avatar answered Oct 12 '22 02:10

Joren