I am trying to clear all existing selections of a property but its not working with a lambda expression.
I have tried using "All" but it return a bool and does not work in this case. How can I accomplish this using lambda?
var permGroup = (ObservableCollection<PermissionGroup>)
this.choicesOptionsTree.ItemsSource;
// NOT WORKING
permGroup.All(pg => pg.Permissions.All);
// WORKING
//clear all existing selections).
foreach (var perGrp in permGroup)
{
foreach (var perm in perGrp.Permissions)
{
perm.Selected = false;
}
}
Kjartan
19.2k16 gold badges75 silver badges102 bronze badges
asked Dec 20, 2012 at 9:16
user1918046
4 Answers 4
You can use:
foreach (var perm in permGroup.SelectMany(x => x.Permissions))
{
perm.Selected = false;
}
answered Dec 20, 2012 at 9:18
leppie
118k18 gold badges201 silver badges300 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Mattias Josefsson
Dosent this just loop thru one permGroups Permissions?
Simon Whitehead
This is the best answer by far because it doesn't make the assumption that the OP will know to cast to a
List<T>.All() is for determining if all elements in the collection satisfy a given condition, not for performing an action on all elements.
You want to use ForEach() -
permGroup.ForEach(pg => pg.Permissions.ForEach(perm => perm.Selected = false));
answered Dec 20, 2012 at 9:19
Dryadwoods
2,9205 gold badges45 silver badges78 bronze badges
4 Comments
Simon Whitehead
ObservableCollection doesn't have a ForEach method.. List<T> does.
Simon Whitehead
You realise he's casting
permGroup to an ObservableCollection<T> yes?Dryadwoods
Yes, I saw it, but the question is, can he change it? or does he really needs to use it in that way?
Simon Whitehead
..perhaps consider casting it to a List and explaining that then? As it stands, your example will not compile.
permGroup.ForEach(pg => pg.Permissions.ForEach(p => p.Selected = false));
answered Dec 20, 2012 at 9:19
Mattias Josefsson
1,1971 gold badge8 silver badges22 bronze badges
3 Comments
Leri
Why are you sure that
pg.Permissions is enumerable?Matías Fidemraizer
@PLB If it's not enumerable you wouldn't be able to use
foreach too :/Leri
@MatíasFidemraizer I have not read complete code. My fault. I thought
All was a property of type of pg.Permissions. :)Here is another couple of ways
permGroup.SelectMany(pg => pg.Permissions).ForEach(x => x.Selected = false);
or
foreach (var permission in groups.SelectMany(x => x.Permissions))
permission.Selected = false;
answered Dec 20, 2012 at 9:24
marto
4,1802 gold badges31 silver badges39 bronze badges
Comments
lang-cs
pg.Permissions.All?