Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Distinct property values from List

Tags:

c#

wpf

db2

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


            }
        }
like image 392
Ben Avatar asked Jan 06 '11 10:01

Ben


People also ask

What is distinct () in C#?

C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).

How to get unique values from Array of objects JavaScript?

One way to get distinct values from an array of JavaScript objects is to use the array's map method to get an array with the values of a property in each object. Then we can remove the duplicate values with the Set constructor. And then we can convert the set back to an array with the spread operator.


1 Answers

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)

like image 77
Marc Gravell Avatar answered Sep 28 '22 06:09

Marc Gravell