0

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 ?

  • 2
    Possible duplicate of [How to Sort a List by a property in the object](http://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – M.kazem Akhgary May 29 '16 at 13:28

3 Answers3

0
Cus.Product = Cus.Product.OrderBy(p => p.ProductNumber).ToList();
Moshezauros
  • 2,493
  • 1
  • 11
  • 15
0

Product class should be implementing CompareTo method in IComparable interface

0

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; }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20