I am trying to get distinct FullNames from a list that contains FullNames and IDs then displaying these in a listBox control. Is there a simple way to do it? Thanks Ben
我试图从包含FullNames和ID的列表中获取不同的FullNames,然后在listBox控件中显示这些。有一个简单的方法吗?谢谢本
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??
}
}
2 个解决方案
#1
18
With LINQ:
使用LINQ:
var uniqueNames = myContacts.Select(c => c.FullName).Distinct().ToList();
should work. If the order is unimportant you could also use:
应该管用。如果订单不重要,您还可以使用:
var names = new HashSet<string>();
while(dr.Read()) {
...
names.Add(contact.FullName);
}
(and then use ToList()
/ OrderBy
whatever you need)
(然后使用ToList()/ OrderBy,无论你需要什么)
#2
0
I think you can use different approaches here:
我想你可以在这里使用不同的方法:
-
Make Sql query that queries distinct values.
进行查询不同值的Sql查询。
-
Check that contact already in list. This approach assume that your class must redefine euqality operator. Or you can check that this contact id is already in list.
检查列表中的联系人。这种方法假设您的类必须重新定义euqality运算符。或者您可以检查此联系人ID是否已列在列表中。
-
Use Linq query as mentioned above.
如上所述使用Linq查询。
#1
18
With LINQ:
使用LINQ:
var uniqueNames = myContacts.Select(c => c.FullName).Distinct().ToList();
should work. If the order is unimportant you could also use:
应该管用。如果订单不重要,您还可以使用:
var names = new HashSet<string>();
while(dr.Read()) {
...
names.Add(contact.FullName);
}
(and then use ToList()
/ OrderBy
whatever you need)
(然后使用ToList()/ OrderBy,无论你需要什么)
#2
0
I think you can use different approaches here:
我想你可以在这里使用不同的方法:
-
Make Sql query that queries distinct values.
进行查询不同值的Sql查询。
-
Check that contact already in list. This approach assume that your class must redefine euqality operator. Or you can check that this contact id is already in list.
检查列表中的联系人。这种方法假设您的类必须重新定义euqality运算符。或者您可以检查此联系人ID是否已列在列表中。
-
Use Linq query as mentioned above.
如上所述使用Linq查询。