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??
}
}
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).
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With