Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of distinct values in List<T> in c#

So, say I have something like the following:

public class Element
{
  public int ID;
  public int Type;
  public Properties prorerty;
  ...
}
and
public class Properties
{
  public int Id;
  public string Property;
  ...
}

and I have a list of these:

List Elements = new List();

What would be the cleanest way to get a list of all distinct values in the prorerty column in Element class? I mean, I could iterate through the list and add all values that aren't duplicates to another list of strings, but this seems dirty and inefficient. I have a feeling there's some magical Linq construction that'll do this in one line, but I haven't been able to come up with anything.

like image 710
Mykhalik Avatar asked Jan 15 '23 06:01

Mykhalik


1 Answers

 var results = Elements.Distinct();

Note: you will have to override .Equals and .GetHashCode()

public class Element : IEqualityComparer<Element>
{
   public bool Equals(Element x, Element y)
   {
     if (x.ID == y.ID)
     {
        return true;
     }
     else
     {
        return false;
     }
   }
}

public int GetHashCode(Element obj)
{
    return obj.ID.GetHashCode();
}
like image 161
Darren Avatar answered Jan 22 '23 08:01

Darren