Live Chat Icon For mobile
Live Chat Icon

How do I filter out duplicate entries in my list when bound to a data source?

Platform: WPF| Category: ItemsControl

The fact that you have duplicate entries probably suggests that you are binding to the wrong data source. But, in any case, there are possibly valid scenarios where this is necessary. Here is a solution.

One way is to group the list by name using CollectionViewSource and then bind the Groups to the ListBox. Here is some code:

(for better code formatting, look at this thread: Distinct Value Filter For ListBox

If you Contracts collection is like this:

public class Contracts : List    
        public Contracts()   
            this.Add(new Contract() { ContractKey = '1', Name = 'John' });   
            this.Add(new Contract() { ContractKey = '2', Name = 'Bill' });   
            this.Add(new Contract() { ContractKey = '3', Name = 'Bill' });   
    public class Contract   
        public string ContractKey { get; set; }   
        public string Name { get; set; }   

Then you can use the CollectionViewSource to bind to it and group the colelction by Name as follows:


This will render the listbox the way you want – ignoring the duplicate names. You can then interpret the selected item as follows:

private void lb_SelectionChanged(object sender, SelectionChangedEventArgs e)   
            CollectionViewGroup groupSelected = ((CollectionViewGroup)e.AddedItems[0]);   
            string name = groupSelected.Name;   
            // These contain the items within the group   

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.