在组合框中,我们将字符串显示为用户的 DisplayMember 和成员的 id(可能对我们很重要)作为我们的 ValueMember。我们有更多时间使用 ids 。我的例子:
class Country
{
public string Name { get; set; }
public int ID { get; set; }
public Country( int i,string s) { Name = s; ID = i; }
}
class ComboItem
{
public string DisplayMember { get; set; }
public int ValueMember { get; set; }
}
class ComboItemEqualityComparer : IEqualityComparer<ComboItem>
{
public bool Equals(ComboItem item1, ComboItem item2)
{
if (item1.ValueMember == item2.ValueMember && item1.DisplayMember == item2.DisplayMember)
{
return true;
}
return false;
}
public int GetHashCode(ComboItem item)
{
string str = item.DisplayMember + item.ValueMember;
return str.GetHashCode();
}
}
测试 :
List<Country> countries = new List<Country> {
new Country(1,"UK"),
new Country(2,"Turkey"),
new Country(8,"Turkey"),
new Country(5,"Turkey"),
new Country(2,"Turkey"),
new Country(3,"USA") ,
new Country(3,"USA")}; //.Distinct(new CountryEqualityComparer()).ToList();
var Data = (from i in countries
select new ComboItem { ValueMember = i.ID, DisplayMember = i.Name }).Distinct(new ComboItemEqualityComparer()).ToList();
cbName.DataSource = Data;
cbName.DisplayMember = "DisplayMember";
cbName.ValueMember = "ValueMember";
有时我们的数据显示名称相同,但它们的 ID 不同。我们可以将 ComboItemEqualityComparer equals 方法更改为:
public bool Equals(ComboItem item1, ComboItem item2)
{
if (item1.ValueMember == item2.ValueMember )
{
return true;
}
return false;
}
请享用。
对于这个问题,我们可以:
....
select new ComboItem { ValueMember = u.UFISID, DisplayMember = u.EmployeeName }).Distinct(new yourIEqualityComparer()).ToList();