C# 对List成员排序的简单方法_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > C# 对List成员排序的简单方法

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

 2013/11/18 17:21:18  MikeLiuHF  博客园  我要评论(0)
  • 摘要:网上看到的方法,实在太方便了,转过来保存,原链接:http://blog.csdn.net/wanzhuan2010/article/details/62058841usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Text;5namespaceListSort6{7classProgram8{9staticvoidMain(string[]args)10{11List<
  • 标签:C# 方法 list

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

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

  1.  1 using System;  
     2 using System.Collections.Generic;  
     3 using System.Linq;  
     4 using System.Text;  
     5 namespace ListSort  
     6 {  
     7     class Program  
     8     {  
     9         static void Main(string[] args)  
    10         {  
    11             List<Customer> listCustomer = new List<Customer>();  
    12             listCustomer.Add(new Customer { name = "客户1", id = 0 });  
    13             listCustomer.Add(new Customer { name = "客户2", id = 1 });  
    14             listCustomer.Add(new Customer { name = "客户3", id = 5 });  
    15             listCustomer.Add(new Customer { name = "客户4", id = 3 });  
    16             listCustomer.Add(new Customer { name = "客户5", id = 4 });  
    17             listCustomer.Add(new Customer { name = "客户6", id = 5 });  
    18             ///升序  
    19             List<Customer> listCustomer1 = listCustomer.OrderBy(s => s.id).ToList<Customer>();  
    20             //降序  
    21             List<Customer> listCustomer2 = listCustomer.OrderByDescending(s => s.id).ToList<Customer>();  
    22             //Linq排序方式  
    23             List<Customer> listCustomer3 = (from c in listCustomer  
    24                                             orderby c.id descending //ascending  
    25                                             select c).ToList<Customer>();  
    26             Console.WriteLine("List.OrderBy方法升序排序");  
    27             foreach (Customer customer in listCustomer1)  
    28             {  
    29                 Console.WriteLine(customer.name);  
    30             }  
    31             Console.WriteLine("List.OrderByDescending方法降序排序");  
    32             foreach (Customer customer in listCustomer2)  
    33             {  
    34                 Console.WriteLine(customer.name);  
    35             }  
    36             Console.WriteLine("Linq方法降序排序");  
    37             foreach (Customer customer in listCustomer3)  
    38             {  
    39                 Console.WriteLine(customer.name);  
    40             }  
    41             Console.ReadKey();  
    42         }  
    43     }  
    44     class Customer  
    45     {  
    46         public int id { get; set; }  
    47         public string name { get; set; }  
    48     }  
    49 }  

     

 

 

效果展示:

发表评论
用户名: 匿名