从列表中获取不同的属性值 [英] Get Distinct property values from List

查看:50
本文介绍了从列表中获取不同的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从包含FullName和ID的列表中获取不同的FullName,然后将其显示在listBox控件中。有简单的方法吗?感谢Ben

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

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();

应该可以。如果顺序不重要,则还可以使用:

should work. If the order is unimportant you could also use:

var names = new HashSet<string>();
while(dr.Read()) {
    ...
    names.Add(contact.FullName);
}

(然后使用 ToList() / OrderBy 无论您需要什么)

(and then use ToList() / OrderBy whatever you need)

这篇关于从列表中获取不同的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆