Order by list in complex object

此生再无相见时 提交于 2021-02-05 10:01:47

问题


I have two classes :

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; }
}

And one instance :

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

I want to sort the Product List and get a Customer with a list of products sorted by ProductNumber

How to do this ?


回答1:


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



回答2:


Product class should be implementing CompareTo method in IComparable interface




回答3:


try this

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; }
    }
}


来源:https://stackoverflow.com/questions/37510407/order-by-list-in-complex-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!