C# 对List成员排序的简单方法

时间:2022-04-22 17:10:00

网上看到的方法,实在太方便了,转过来保存,原链接:

http://blog.csdn.net/wanzhuan2010/article/details/6205884

  1.  using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace ListSort
    {
    class Program
    {
    static void Main(string[] args)
    {
    List<Customer> listCustomer = new List<Customer>();
    listCustomer.Add(new Customer { name = "客户1", id = });
    listCustomer.Add(new Customer { name = "客户2", id = });
    listCustomer.Add(new Customer { name = "客户3", id = });
    listCustomer.Add(new Customer { name = "客户4", id = });
    listCustomer.Add(new Customer { name = "客户5", id = });
    listCustomer.Add(new Customer { name = "客户6", id = });
    ///升序
    List<Customer> listCustomer1 = listCustomer.OrderBy(s => s.id).ToList<Customer>();
    //降序
    List<Customer> listCustomer2 = listCustomer.OrderByDescending(s => s.id).ToList<Customer>();
    //Linq排序方式
    List<Customer> listCustomer3 = (from c in listCustomer
    orderby c.id descending //ascending
    select c).ToList<Customer>();
    Console.WriteLine("List.OrderBy方法升序排序");
    foreach (Customer customer in listCustomer1)
    {
    Console.WriteLine(customer.name);
    }
    Console.WriteLine("List.OrderByDescending方法降序排序");
    foreach (Customer customer in listCustomer2)
    {
    Console.WriteLine(customer.name);
    }
    Console.WriteLine("Linq方法降序排序");
    foreach (Customer customer in listCustomer3)
    {
    Console.WriteLine(customer.name);
    }
    Console.ReadKey();
    }
    }
    class Customer
    {
    public int id { get; set; }
    public string name { get; set; }
    }
    }

效果展示:

C# 对List成员排序的简单方法