Reputation: 363
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"/>
...
Upvotes: 1
Views: 1677
Reputation: 1338
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.
Upvotes: 2
Reputation: 236208
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>
Upvotes: 3