按复杂对象中的列表排序

时间:2016-05-29 13:22:28

标签: c# linq sorting

我有两个班级:

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

    public string LastName { get; set; }

    public List<Product> Product { get; set; }
}

public class Product
{
    public int ProductNumber { get; set; }

    public string ProductColor { get; set; }
}

还有一个例子:

Customer Cus = new Customer()
{
    FirstName = "FirstName1",
    LastName = "LastName1",
    Product = new List<Product>
    {
        new Product()
        {
            ProductColor = "ProductColor12",
            ProductNumber = 12
        },
        new Product()
        {
            ProductColor = "ProductColor11",
            ProductNumber = 11
        }
    }
};

我想对产品列表进行排序,并为客户提供按ProductNumber

排序的产品列表

怎么做?

3 个答案:

答案 0 :(得分:0)

Cus.Product = Cus.Product.OrderBy(p => p.ProductNumber).ToList();

答案 1 :(得分:0)

产品类应该在IComparable接口

中实现CompareTo方法

答案 2 :(得分:0)

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Customer> customers = new List<Customer>();
            Customer Cus = new Customer()
            {
                FirstName = "FirstName1",
                LastName = "LastName1",
                Product = new List<Product> {
                    new Product()
                    {
                        ProductColor = "ProductColor12",
                        ProductNumber = 12
                    },
                    new Product()
                    {
                        ProductColor = "ProductColor11",
                        ProductNumber = 11
                    }
                }
            };
            customers.Add(Cus);

            var results = customers.OrderBy(x => x.LastName).ThenBy(y => y.FirstName).Select(z => z.Product.OrderBy(a => a.ProductNumber)).ToList();

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

        public string LastName { get; set; }

        public List<Product> Product { get; set; }
    }

    public class Product
    {
        public int ProductNumber { get; set; }

        public string ProductColor { get; set; }
    }
}