1

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
3
  • What is pg.Permissions.All ? Commented Dec 20, 2012 at 9:17
  • It looks like you're merely calling a property, and not a method call. Commented Dec 20, 2012 at 9:18
  • @leppie Permissions seems to be another enumeration and All would be the LINQ-ALL Commented Dec 20, 2012 at 9:19

4 Answers 4

2

You can use:

foreach (var perm in permGroup.SelectMany(x => x.Permissions))
{
 perm.Selected = false;
}
answered Dec 20, 2012 at 9:18
Sign up to request clarification or add additional context in comments.

2 Comments

Dosent this just loop thru one permGroups Permissions?
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>.
1

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

4 Comments

ObservableCollection doesn't have a ForEach method.. List<T> does.
You realise he's casting permGroup to an ObservableCollection<T> yes?
Yes, I saw it, but the question is, can he change it? or does he really needs to use it in that way?
..perhaps consider casting it to a List and explaining that then? As it stands, your example will not compile.
0
permGroup.ForEach(pg => pg.Permissions.ForEach(p => p.Selected = false)); 
answered Dec 20, 2012 at 9:19

3 Comments

Why are you sure that pg.Permissions is enumerable?
@PLB If it's not enumerable you wouldn't be able to use foreach too :/
@MatíasFidemraizer I have not read complete code. My fault. I thought All was a property of type of pg.Permissions. :)
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.