I'm trying to get items in C# in an ObservableCollection<MyClassSelectable>
using Linq and Lambda in the following cases :
Or
MyClassSelectable
has a property named Selected
of bool
type.
Is it possible to do it, in only one Linq query line ?
Thank you.
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();