我有如下的 linq 查询
string sortby="Date"; //it can be name or something else as well
var query=(from t in Uow.Transactions.GetAllWithReferences()
orderby t.Date descending
select t);
但我想根据 sortby 变量值以不同方式排序。我如何使用 Linq 做到这一点?
最佳答案
对于示例类:
private class Tst
{
public int field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
}
你可以这样做:
var index = 1;
var sortedList = (from l in list
orderby index == 1 ? l.field1.ToString() : index == 2 ? l.field2 : l.field3
select l);
但是由于字段有不同的类型,您必须像 l.field1.ToString()
使用 lambda 的方法是:
var sortedList =
list.OrderBy(l =>
index == 1 ? l.field1.ToString()
: index == 2 ? l.field2
: l.field3)
.Select(l => l).ToList();
关于c# - 如何使用 Orderby 创建动态 linq 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15409788/