代码之家  ›  专栏  ›  技术社区  ›  abatishchev Karl Johan

在LINQ查询中避免双重控制搜索

  •  1
  • abatishchev Karl Johan  · 技术社区  · 15 年前

    我有一个 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。

    4 回复  |  直到 15 年前
        1
  •  2
  •   STO    15 年前
    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
  •  3
  •   Mehrdad Afshari    15 年前
    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。

        3
  •  1
  •   Amy B    15 年前

    看,没有匿名实例(不过,几乎没有更好的方法,更新组并枚举两次)

    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那么简单,如果
        4
  •  0
  •   abatishchev Karl Johan    15 年前

    和大卫的想法一样,但是 字符串:

    (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