我正在尝试从包含全名和 ID 的列表中获取不同的全名,然后将它们显示在列表框控件中。有简单的方法吗?谢谢本
using (DB2DataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
Contact contact = new Contact();
contact.ContactID = Convert.ToInt32(dr["CONTACT_ID"]);
contact.FullName= dr["FULL_NAME"].ToString();
myContacts.Add(contact);
//contactsListBox.ItemsSource = myContacts.Distinct FullName??
}
}
最佳答案
使用 LINQ:
var uniqueNames = myContacts.Select(c => c.FullName).Distinct().ToList();
应该可以。如果顺序不重要,您还可以使用:
var names = new HashSet<string>();
while(dr.Read()) {
...
names.Add(contact.FullName);
}
(然后根据需要使用 ToList()
/OrderBy
)
关于c# - 从列表中获取不同的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4613738/