Get Distinct property values from List
Asked Answered
N

3

14

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??


            }
        }
Nonjuror answered 6/1, 2011 at 10:3 Comment(0)
S
23

With 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)

Supple answered 6/1, 2011 at 10:5 Comment(2)
Thanks alot! And how about the ItemsSource what should that be set to?Nonjuror
Thanks I had tried that but no luck will play around with it.Nonjuror
T
0

I think you can use different approaches here:

  1. Make Sql query that queries distinct values.

  2. 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.

  3. Use Linq query as mentioned above.

Tiernan answered 6/1, 2011 at 10:15 Comment(1)
Cheers I went for the Linq optionNonjuror
S
0

we can achieve like this:

var distinctItems = myItemsList.ToList().DistinctBy(x => x.ItemName);
Subgroup answered 30/8, 2023 at 10:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.