对在ASP.NET中进一步具有对象的对象列表进行排序

时间:2013-12-25 11:24:02

标签: c# asp.net linq sorting gridview

我有一个对象列表,它还包含对象 对于例如。

Class Customer{
    string name;
    Address addr;
}

Class Address
{
    string city;
    string state;
}

现在我有一个绑定到gridview的Customer对象列表。

| Name | city | State |

我想根据城市和州对网格视图列进行排序。 我将如何做到。

我试过

var param = Expression.Parameter(typeof(Customer), e.SortExpression);
var sortExpression = Expression.Lambda<Func<Customer, object>>(
    Expression.Convert(Expression.Property(param, e.SortExpression),typeof(object)), param);

但是当排序表达式是city时,它不会排序。

1 个答案:

答案 0 :(得分:4)

以下是我的样本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        var list = new List<Customer>();

        list.Add(new Customer()
        {
            FirstName = "ztest",
            LastName = "ztest1",
            Address = new Address()
            {
                City = "Kiev"
            }
        });
        list.Add(new Customer()
        {
            FirstName = "test",
            LastName = "test1",
            Address = new Address()
            {
                City = "New York"
            }
        });


        string sortExpressionField = "Address.City";


        var props = sortExpressionField.Split('.');
        var inParam = Expression.Parameter(typeof(Customer));
        var param = props.Aggregate<string, Expression>(inParam, Expression.Property);
        var sortExpression = Expression.Lambda<Func<Customer, object>>(param, inParam);

        var sorted = list.AsQueryable<Customer>().OrderBy(sortExpression);
        foreach (var item in sorted)
        {
            Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
        }
    }

}

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string City { get; set; }
}

以下是验证其有效的链接 - http://dotnetfiddle.net/iQSTBR

<强> UPDATE1

对于复杂的情况,您需要解析属性,然后导航到最后一个属性。我已经更新了代码,这里的示例适用于子属性 - http://dotnetfiddle.net/alTWPK

<强> UPDATE2

 var selectedNew = selected
       .AsQueryable<Customer>()
       .OrderBy(sortExpression)
       .ToList();
 gdvEmployees.DataSource = selectedNew; 
 gdvEmployees.DataBind();