Search code examples
c#asp.netlinqextension-methodsfindcontrol

Avoid double control search in LINQ query


I have a Dictionary<string, bool> where key - control's ID and value - it's visible status to set:

var dic = new Dictionary<string, bool>
{
    { "rowFoo", true},
    { "rowBar", false },
    ...
};

Some of controls can be null, i.e. dic.ToDictionary(k => this.FindControl(k), v => v) will not work because key can't be null.

I can do next:

dic
    .Where(p => this.FindControl(p.Key) != null)
    .ForEach(p => this.FindControl(p.Key).Visible = p.Value); // my own extension method

but this will call FindControl() twice for each key.

How to avoid double search and select only those keys for which appropriate control exists?

Something like:

var c= FindControl(p.Key);
if (c!= null)
    return c;

but using LINQ.


Solution

  • dic
     .Select(kvp => new { Control = this.FindControl(kvp.Key), Visible = kvp.Value })
     .Where(i => i.Control != null)
     .ToList()
     .ForEach(p => { p.Control.Visible = p.Visible; });