Looping through session variables with LINQ?

So, I'm still pretty new to LINQ, so bear with me. I am trying to check session variables, and if the variable name does not contain a key with the name "Selected", then set it to null.

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

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

Thanks for the help.

+3
source share
3 answers

LINQ, which you have, is set to null. I believe that this is what you need to set the value:

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

Here is the full extended form of LINQ

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

In this particular case, I find the combination of LINQ and foreachmore readable:

foreach (var key in Session.Keys.Cast<string>().Where(k => !k.Contains("Selected").ToList())) {
  Session[key] = null;
}
+3
source

Here's an alternative, more functional solution:

Session = Session.ToDictionary(it => it.Key, 
              it => (it.Key as string).Contains("Selected") ? it.Value : null);

The trade-off is to create a new dictionary.

0
source

All Articles