I have a CollectionViewSource
whose source is an ObservableCollection.
On a List
or ObservableCollection
, I can use linq to group my objects, and sum their quantities, but how is it possible to do it on a CollectionViewSource(if it is possible), I see nowhere any documentation about it.
For now I only can manage grouping using :
ProductsView.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
But I see nowhere information on how to display a sum, or maximum/minimum value of a field?
Edit :
Concretely, I want to do equivalent of that :
liste_ass = liste_ass.GroupBy(l => l.Name)
.Select(cl => new Assemblage
{
Quantite = cl.Sum(c => c.Quantite),
ID = 0,
IdAffaire = cl.First().IdAffaire,
Name = cl.First().Name,
Priorite = 0,
Dessin = cl.First().Dessin,
Groupe = cl.First().Groupe,
Priorite = cl.Max(c=>c.Priorite),
ListeIdOperations = cl.First().ListeIdOperations,
}).ToList();
This is what I would do in linq. But reading about ICollectionView, it seems this is not possible to do that on ICollectionView, as it is a view, and no operation can be done on them.
You can access every CollectionViewGroup
which contains all the group's imformation including ItemCount
through CollectionView.Groups
property. If you want to create a custom group header and show it on UI, here is a sample:
<ListBox ItemsSource="{Binding your view}">
<ListBox.Resources>
<local:ToAssemblageConverter x:Key="toAssemblageConverter"/>
</ListBox.Resources>
<ListBox.GroupStyle>
<GroupStyle HidesIfEmpty="True">
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
DataContext="{Binding Items, Converter={StaticResource ResourceKey=toAssemblageConverter}}">
<TextBlock Margin="5 0" Text="{Binding Quantite}"/>
<TextBlock Margin="5 0" Text="{Binding Id}"/>
...
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
public class ToAssemblageConverter : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var cl = (IEnumerable)value;
return new Assemblage() {
Quantite = cl.Sum(c => c.Quantite),
ID = 0,
IdAffaire = cl.First().IdAffaire,
Name = cl.First().Name,
Priorite = 0,
Dessin = cl.First().Dessin,
Groupe = cl.First().Groupe,
Priorite = cl.Max(c=>c.Priorite),
ListeIdOperations = cl.First().ListeIdOperations,
}
}
}