Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through session variables with LINQ?

Tags:

linq

session

So I'm still rather new to LINQ, so bear with me. I'm trying to check the session variables and if the variable name doesn't contain the key with the name "Selected" then set the value of it to null.

This is what I have, though I'm probably not close:

Session.Keys.Cast<string>().Where(k => !k.Contains("Selected")).ToList().ForEach(k => k = null);

Thanks for the assistance.

like image 725
Ber53rker Avatar asked Dec 16 '22 23:12

Ber53rker


2 Answers

The LINQ you have is setting the key to null. I believe this is what you need to actually set the value:

Session.Keys.Cast<string>()
            .Where(k => !k.Contains("Selected"))
            .ToList()
            .ForEach(k => Session[k] = null);
                          ^
like image 66
Robaticus Avatar answered Jun 06 '23 18:06

Robaticus


Here is the full expanded LINQ form

Session.Keys
  .Cast<string>()
  .Where(k => !k.Contains("Selected")
  .ToList()
  .ForEach(k => Session[k] = null);

For this particular case I find a mix of LINQ and foreach to be much more readable:

foreach (var key in Session.Keys.Cast<string>().Where(k => !k.Contains("Selected").ToList())) {
  Session[key] = null;
}
like image 42
JaredPar Avatar answered Jun 06 '23 17:06

JaredPar