2010-06-23 5 views
1

LINQ 쿼리에서 이중 제어 검색을 방지 Dictionary<string, bool> 경우 키 - 컨트롤의 ID 및 가치 - 그것은 눈에 보이는 상태를 설정하는 것 :내가 가진

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

컨트롤의 일부, 즉 dic.ToDictionary(k => this.FindControl(k), v => v) 키가 할 수 있기 때문에 작동하지 않습니다, null 될 수 있습니다 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를 사용하여.

답변

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

...하지만 단순히 ifforeach을 사용하십시오. 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; 
    } 
} 
  • 포기하는
0

foreach는-경우 같은 생각에 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