c# - 如何使用 Orderby 创建动态 linq 查询?

标签 c# linq

我有如下的 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/

相关文章:

c# - .ThenBy 是如何实现的?

c# - 在 InnoSetup 中访问 C# COM 对象时出现异常

c# - 在调用 read() 之前(也在调用 read 之后)访问字段的尝试无效

c# - WPF:单击按钮打开新窗口

c# - 使用 Sql Functions.Patindex 进行多列的 Linq 通配符搜索

c# - C# Visual Studio 2017 版本 15.1.1 中的 Linq 查询内部的 string Text.ToUpper() 速度较慢

c# - 将 C++ dlib 项目链接到 C#

c# - 如何获取数组中类的属性

c# - Linq to Entities删除

c# - Entity Framework Linq何时查询Hints Sql数据库?