我有一个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。
答案 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);
...但我只是将foreach
与if
语句一起使用。不要过度使用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;
}
}
答案 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