[英]Avoid double control search in LINQ query
我有一個Dictionary<string, bool>
,其中鍵-控件的ID和值-要設置的可見狀態:
var dic = new Dictionary<string, bool>
{
{ "rowFoo", true},
{ "rowBar", false },
...
};
一些控件可以為null
,例如dic.ToDictionary(k => this.FindControl(k), v => v)
將不起作用,因為key不能為null。
我可以下一步:
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。
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。
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; });
看,沒有匿名實例(雖然更好,但新建組並枚舉兩次)
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;
}
}
同樣的想法,然后大衛的,但在一個字符串:
(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.