how to show distinct attribute value in a ComboBox using LINQ?

c# dynamic-linq linq wpf

Question

this is the Book class Book{BookId, Title, Category, Quantity}; So, how would i select only one object from each category using linq query? i tryed like this,

this.catagoryList.DataContext = ldc.Books.Distinct(); //categoryList is a ComboBox

but you know it doesn't work. All of these objects are unique, so it shows same category for many time. Actually i want it like GroupBy, but i would like to select only one objects from each group to show unique categories in the ComboBox. Thanks.

XAML:

    <DataTemplate x:Key="CatagoryTemplate">
          <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Catagory}"/>
          </StackPanel>
    </DataTemplate>
...
 <ComboBox Name="catagoryList" ItemsSource="{Binding}" ItemTemplate="{StaticResource CatagoryTemplate}" SelectionChanged="catagoryList_SelectionChanged" IsSynchronizedWithCurrentItem="True"/>
...
1
1
11/26/2012 8:54:15 PM

Accepted Answer

this.catagoryList.DataContext = ldc.Books.Select(b => b.Category).Distinct();

If you don't want to change your template:

catagoryList.DataContext = ldc.Books.Select(b => b.Category)
                                    .Distinct()
                                    .Select(c => new { Catagory = c });

But I think it's better to change template to match strings.

<DataTemplate x:Key="CatagoryTemplate">
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding}"/>
      </StackPanel>
</DataTemplate>
3
11/26/2012 8:46:42 PM

Popular Answer

While context of this code isn't clear, in general, you should probably leave the ComboBox's DataContext alone and bind its ItemsSource property to a property in your view model that returns your linq query.

That said, in your specific code, you just have to Select() the Category before you call Distinct():

this.catagoryList.DataContext = ldc.Books.Select(book=>book.Category).Distinct();

EDIT:

Just remove your DataTemplate, it is not useful. If you set your DataContext to the LINQ query above and then bind ItemsSource to the DataContext as you are doing, it will display the list of strings properly.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow