代码之家  ›  专栏  ›  技术社区  ›  driAn

LINQ查询中的C#lambda表达式

  •  2
  • driAn  · 技术社区  · 16 年前

    我知道循环中的lambda表达式如果使用局部变量会导致问题。(见 http://www.jaylee.org/post/2008/11/18/Lambda-Expression-and-ForEach-loops.aspx )

    现在有一种情况,我在LINQ查询中使用lambda表达式:

    var products = from product in allProducts
                   select new
                   {
                      ID = product.ID,
                      Name = product.Name,
                      Content = new Func<object,string>(
                         (obj) => (GetSomeDynamicContent(obj, product))
                         )
                   };
    
    someCustomWebControl.DataSource = products;
    someCustomWebControl.DataBind();
    

    1 回复  |  直到 16 年前
        1
  •  2
  •   dtb    16 年前

    是的,这样做很安全。LINQ查询基本上扩展为:

    private AnonType AnonMethod(Product product)
    {
        return new
            {
                ID = product.ID,
                Name = product.Name,
                Content = new Func<object,string>(
                    (obj) => (GetSomeDynamicContent(obj, product))
                    )
            };
    }
    
    var products = allProducts.Select(AnonMethod);
    someCustomWebControl.DataSource = products;
    someCustomWebControl.DataBind();
    

    如您所见,lambda表达式捕获 product 所有产品中每个产品的变量。