C# 封装LINQ select语句

C# 封装LINQ select语句,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,我的LINQ声明如下所示: return ( from c in customers select new ClientEntity() { Name = c.Name, ... }); return ( from c in customers select new Mapper(c)); private static readonly Expression<Func<CustomerInfo, string>> GetName = c => c.Name;

我的LINQ声明如下所示:

return ( from c in customers select new ClientEntity() { Name = c.Name, ... });
return ( from c in customers select new Mapper(c));
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);
我希望能够将select抽象为它自己的方法,这样我就可以有不同的“映射”选项。我的方法需要返回什么

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

return ( from c in customers select new ClientEntity() { Name = c.Name, ... });
return ( from c in customers select new Mapper(c));
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);
编辑:


这是用于LINQtoSQL的。

这是用于LINQtoObject的?还是为了一只林肯


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

您可能必须使用链式方法,而不是使用LINQ语法,然后才能传入您指定的任何一种
值:

Expression<Func<CustomerTable, Customer>> someMappingExpression = c => new Customer { Name = c.Name };
return context.CustomerTable.Select(someMappingExpression);
Expression someMappingExpression=c=>newcustomer{Name=c.Name};
返回context.CustomerTable.Select(someMappingExpression);
更新:采用
函数,而不是
表达式

更新:应该使用的函数确实采用了
表达式,而不仅仅是
函数

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

如果查看在
IQueryable
上工作的Select版本,它不需要
Func
。相反,它采用
表达式
。编译器知道如何从lambda生成这样的东西,这就是您的普通代码进行编译的原因

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

return ( from c in customers select new ClientEntity() { Name = c.Name, ... });
return ( from c in customers select new Mapper(c));
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);

顺便说一句:这里描述的解决方案只有在您希望在单独的查询子句(例如Select)中使用代码的“分解”部分时才有效。如果您想将其用作同时执行其他操作的子句的一部分(可能返回包含其他信息的匿名类型),则需要使用expression.Xyz方法动态构建整个表达式树

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


本例中的代码示例是语法错误,不是吗?另外,注释“Select接受一个FUnc,而不是表达式”对于Linq to SQL是不正确的。在测试了您的解决方案和bdukes之后,我必须说您的解决方案更好,因为它能够解析表达式并实际使用它构建SQL。bdukes'带来所有结果,然后在内存中应用其他子句。