2010-06-23 104 views
1

我有一个Dictionary<string, bool>,其中关键 - 控件的ID和价值 - 它是可见的状态设置:避免在LINQ查询双控搜索

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。

回答

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

看,没有匿名实例(几乎没有更好虽然,newing行动组和枚举两次)

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,如果
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