简体   繁体   中英

Filter duplicates from a list to populate ComboBox

I've been looking for a way to filter out duplicates from a list to populate a form, but so far all I have found are to create a duplicate list with either a Hashset or other methods that involve grouping the duplicates into separate list, however I'm not interested in keeping the extras.

Currently what I'm getting in my combobox is:

123
123
456
456
789
789

etc... Trouble is, I'm collecting the data in models (or classes) as such:

List<ModelName>

ModelName<1>
{
   string Name = Bob;
   int Number = 123;
}
ModelName<2>
{
   string Name = Jim;
   int Number = 123;
}
ModelName<3>
{
   string Name = Bob;
   int Number = 456;
}

Is there a way to fill a list with unique classes:

ModelName<1>
{
    Name; 
    Number;
}
ModelName<2>
{
    Name;
}
ModelName<3>
{
    Number;
}

and just filter out and dispose of any double ups?

You can use the LINQ Distinct operator to remove duplicates from a collection:

var listWithoutDuplicates = listWithDuplicates.Distinct().ToList();

If you want to customize the way elements are compared for equality you can use the overload that requires an IEqualityComparer<T> .

In your case, if you want to define "equality" as having the same value of the Location property you can use this EqualityComparer :

class EqualityComparer : IEqualityComparer<ClassName> {

  public Boolean Equals(ClassName x, ClassName y) {
    return Equals(x.Location, y.Location);
  }

  public Int32 GetHashCode(ClassName obj) {
    return obj.Location.GetHashCode();
  }

}

And to get distinct items by location:

var listWithoutDuplicates = listWithDuplicates.Distinct(new EqualityComparer).ToList();
yourList.GroupBy(x => x.Location).Select(x => x.First());

使用list.distinct()并填充列表

  List<int> distinct = list.Distinct().ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM