C# 基于字符串为OrderBy创建lambda表达式
方法MyMethod作为字符串参数。根据这个参数的值,我想返回一个表达式,用于OrderBy。我找不到表达式的正确语法,无法将字典用作TValue类型 更新:C# 基于字符串为OrderBy创建lambda表达式,c#,.net,linq,lambda,C#,.net,Linq,Lambda,方法MyMethod作为字符串参数。根据这个参数的值,我想返回一个表达式,用于OrderBy。我找不到表达式的正确语法,无法将字典用作TValue类型 更新: var dico = new Dictionary<string, Expression<Func<Person, xxxxx>>> { { "property1", x => x.Name}, { "property2", x => x.Age}, }; 谢谢,我想您可能
var dico = new Dictionary<string, Expression<Func<Person, xxxxx>>>
{
{ "property1", x => x.Name},
{ "property2", x => x.Age},
};
谢谢,我想您可能会从以下内容中得到提示:
public void MyMethod(string orderBy)
{
// Assuming Product has 'Name' and 'Age' property ?
var dico = new Dictionary<string, Expression<Func<Product,object>>>
{
{ "property1", x => x.Name},
{ "property2", x => x.Age},
};
Expression<Func<Product,object>> myorder;
dico.TryGetValue(orderBy, out myOrder);
_context.Products.OrderBy(myOrder);
}
你怎么知道x的名字?字典中x的类型是什么?如果x是学生,您最多可以通过以下方式声明字典:newDictionary@mshsayem请参阅我的更新,但替换xxxxx的内容是什么?因为可能有不同类型的属性,所以应该是ObjectNow。如果这是一个在Person上运行的表达式,您不能使用它来订购某些产品,正如在_context.Prodcuts.OrderBy中一样,“'may get hints'意味着这并不是一个真正的答案。特别是因为至少有一个查询提供程序EF6(例如)不允许您对值类型的columbseIt执行此操作,这与EF无关,只是一个linq问题。我通过列表更改了_上下文。
public void MyMethod(string orderBy)
{
// Assuming Product has 'Name' and 'Age' property ?
var dico = new Dictionary<string, Expression<Func<Product,object>>>
{
{ "property1", x => x.Name},
{ "property2", x => x.Age},
};
Expression<Func<Product,object>> myorder;
dico.TryGetValue(orderBy, out myOrder);
_context.Products.OrderBy(myOrder);
}