LastTribunal LastTribunal - 5 months ago 19
C# Question

Changing all values in a lambda/LINQ

I have a dictionary of a list of objects that looks like this

class Client
public int Hash { get; set; }
public bool Active { get; set; }
var ClientsDict = new Dictionary<string, List<Client>>();

I have no problem setting a single record value in the list

ClientsDict[userId].First(a => a.Hash == hash).Active = true;

How do I do the inverse of that and set all the others in the list to false?

ClientsDict[userId].All().Active = false; //cannot resolve symbol

Note: I wanna avoid a foreach


ClientsDict[userId].ForEach(a => a.Active = false); //this works


If you're mutating things you shouldn't be expressing it as a LINQ transformation. Just use a regular foreach loop:

foreach(var client in ClientsDict[userId])
    client.Active = false;

You can also use the List<T>.ForEach method, but I would advise against it.