代码之家  ›  专栏  ›  技术社区  ›  Esteban Araya

封装LINQ select语句

  •  2
  • Esteban Araya  · 技术社区  · 16 年前

    我的LINQ声明如下所示:

    return ( from c in customers select new ClientEntity() { Name = c.Name, ... });
    

    我希望能够将select抽象为它自己的方法,这样我就可以有不同的“映射”选项。我的方法需要返回什么?

    本质上,我希望我的LINQ查询如下所示:

    return ( from c in customers select new Mapper(c));
    

    编辑:

    这是用于LINQ到SQL的。

    4 回复  |  直到 16 年前
        1
  •  4
  •   Daniel Earwicker    16 年前

    新答案现在我注意到它是Linq to SQL…:)

    如果您查看在上工作的Select版本 IQueryable<T> Func<In, Out> . 相反,这需要一段时间 Expression<Func<In, Out>>

    因此,要通过将各种选择映射函数传递给select来准备好使用它们,您可以这样声明它们:

    private static readonly Expression<Func<CustomerInfo, string>> GetName = c => c.Name;
    
    private static readonly Expression<Func<CustomerInfo, ClientEntity>> GetEntity = c => new ClientEntity { Name = c.Name, ... };
    

    var names = customers.Select(GetName);
    
    var entities = customers.Select(GetEntity);
    
        2
  •  1
  •   bdukes Jon Skeet    16 年前

    您可能必须使用链式方法,而不是使用LINQ语法,然后才能传入各种 Expression < Func<TSource, TResult> >

    Expression<Func<CustomerTable, Customer>> someMappingExpression = c => new Customer { Name = c.Name };
    return context.CustomerTable.Select(someMappingExpression);
    

    更新: Select 需要 Func ,而非
    更新: 这个 Select 休息 Expression<Func> Func .

        3
  •  0
  •   Frans Bouma    16 年前

    这是用于linq to对象的?还是为了一只林肯?

    因为选择新映射器(c),要求“c”已具体化为一个对象,然后传递给映射器()。(因为“c”在db级别不为人所知,仅在.NET级别为人所知)

        4
  •  0
  •   Tomas Petricek    15 年前

    表达式.Xyz 方法。

    或者,您可以使用我在这里描述的嵌入lambda表达式的技巧: