Search code examples
c#linqlambdaitems

How can I return in a ObsevableCollection<T> using C# Linq, all items if no one is selected or just selected items if at least one is selected?


I'm trying to get items in C# in an ObservableCollection<MyClassSelectable> using Linq and Lambda in the following cases :

  • Returns All items if no one is selected

Or

  • Returns just selected items if at least one is selected.

MyClassSelectable has a property named Selected of bool type.

Is it possible to do it, in only one Linq query line ?

Thank you.


Solution

  • You can first group by the Selected property. This will get you 2 groups if there are selected and not-selected items OR 1 group if all items are either selected or not-selected. Then, order the groups by the selected property. This will put the group with selected items in the first place if there are 2 groups. Then, return the first group.

    ObservableCollection<MyClassSelectable> myClassesSelectable;
    
    List<MyClassSelectable> result = myClassesSelectable
        // group by the Selected property
        .GroupBy(mcs => mcs.Selected)
        // order (=> true first, false second)
        .OrderByDescending(g => g.Key)
        // return the first
        .FirstOrDefault()
        ?.ToList();