动态linq OrderBy对我不起作用

时间:2014-10-14 23:45:09

标签: c# linq sorting odata

我无法动态指定要排序的列和方向。 我目前有以下代码:

if (sort != "OrderID")
{
    if (sort == "EmployeeName")
    {
        sort = "Employee.FirstName"; //sort by Employee FirstName
    }
    else
    {
        sort = "Customer." + sort; //Customer.CompanyName sort
    }
}

var sortCriteria = string.Format("{0} {1}", sort, sortDir);
var res1 = nwd.Orders //response
    .OrderBy(o => sort+" "+sortDir)
    .ThenBy(o => o.OrderID)
    .Skip((page - 1) * rowsPerPage)
    .Take(rowsPerPage)
    .Select(o => new
    {
        o.OrderID,
        o.Customer.CompanyName,
        o.Customer.ContactName,
        o.Employee.FirstName,
        o.Employee.LastName,
        o.Order_Details
    }).ToList();

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

这个怎么样?

var res1 = nwd.Orders //response

IOrderedQueryable<Orders> result;

if (sort != "OrderID")
{
    if (sort == "EmployeeName")
    {
        result = res1.OrderBy(o => o.Employee.FirstName);
    }
    else
    {
        result= res1.OrderBy(o => o.Customer.CompanyName);
    }
}

result = result.ThenBy(o => o.OrderID)
             .Skip((page - 1) * rowsPerPage)
             .Take(rowsPerPage)
             .Select(o => new
             {
                 o.OrderID,
                 o.Customer.CompanyName,
                 o.Customer.ContactName,
                 o.Employee.FirstName,
                 o.Employee.LastName,
                 o.Order_Details
             }).ToList();

答案 1 :(得分:0)

好的,这是一个带有虚拟类的工作示例:

internal class Program
{
    private static void Main(string[] args)
    {
        var list_people = new List<Person> {
              new Person() {Age = 4, Name = "yo"}, 
              new Person() {Age = 5, Name = "a"}  
        };

        var dynamic_propretry = typeof (Person).GetProperty("Name");
        var sorted = list_people.OrderBy(person => dynamic_propretry.GetValue(person, null));

        foreach (var person in sorted)
        {
            Console.Out.WriteLine(person);
        }

        Console.ReadLine();
    }
}

public class Person{

 public int Age { get; set; }
 public string Name { get; set; }
    public override string ToString()
    {
        return Name + ":" + Age;
    }
} 

因此,您所要做的就是将所需的属性存储在字符串中,并使用我使用"Name"的字符串。它应该工作。