1

我有一个Dictionary<string, bool>where 键 - 控件的 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

4 回答 4

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

...但我会简单地使用foreachwithif声明。不要过度使用 LINQ。

于 2010-06-23T20:47:02.803 回答
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; });
于 2010-06-23T20:47:58.870 回答
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那么简单
于 2010-06-24T01:17:55.287 回答
0

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

(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
于 2010-06-24T09:49:07.167 回答