避免在LINQ查询中进行双重控制搜索

时间:2010-06-23 20:43:51

标签: c# asp.net linq extension-methods findcontrol

我有一个Dictionary<string, bool>,其中键 - 控件的ID和值 - 设置的可见状态:

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

某些控件可能是null,即dic.ToDictionary(k => this.FindControl(k), v => v)无效,因为键不能为空。

我可以做下一个:

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

但这会为每个密钥调用FindControl()两次。

如何避免双重搜索并仅选择存在适当控制的那些键?

类似的东西:

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

但使用LINQ。

4 个答案:

答案 0 :(得分:3)

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

...但我只是将foreachif语句一起使用。不要过度使用LINQ。

答案 1 :(得分:2)

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; });

答案 2 :(得分:1)

看,没有匿名实例(虽然不是更好,新组和枚举两次)

IEnumerable<IGrouping<bool, Control>> visibleGroups = 
  from kvp in controlVisibleDictionary
  let c = this.FindControl(kvp.Key)
  where c != null
  group c by kvp.Value;

foreach(IGrouping<bool, Control> g in visibleGroups)
{
  foreach(Control c in g)
  {
    c.Visible = g.Key;
  }
}
  • 免责声明,不像foreach-if
  • 那么简单

答案 3 :(得分:0)

与David相同的想法,但在一个字符串中:

(from p in new System.Collections.Generic.Dictionary<string, bool>
{
    { "rowAddress", value },
    { "rowTaxpayerID", !value },
    { "rowRegistrationReasonCode", !value },
    { "rowAccountID", !value },
    { "rowAccountIDForeign", value },
    { "rowBankAddress", value },
    { "rowBankID", !value },
    { "rowBankSwift", value },
    { "rowBankAccountID", !value }
}
let c = this.FindControl(p.Key)
where c != null
select new // pseudo KeyValuePair
{
    Key = c,
    Value = p.Value
}).ForEach(p => p.Key.Visible = p.Value); // using own ext. method