当前位置:编程学习 > ASP.NET> 正文

list使用linq排序

时间:2015-5-11类别:编程学习

list使用linq排序

list使用linq排序

List排序实例一

 

  •  
  • C# 代码   复制
  • 
             private static void SortByLinq()
            {
                List<Article> list = GetArticleList();
                var sortedList =
                   (from a in list
                    orderby a.SortIndex, a.Comments
                    select a).ToList();
            }
    
    		
  •  

    List排序实例

     

  •  
  • C# 代码   复制
  • 
             private static void SortByExtensionMethod()
            {
                List<Article> list = GetArticleList();
                var sortedList = list.OrderBy(a => a.SortIndex).ThenBy(a => a.Comments);
                sortedList.ToList(); //这个时候会排序
             }
    		
  •  

    List排序实例

     

  •  
  • C# 代码   复制
  • 
    
    
    static void Main(string[] args) 
    { 
      List listCustomer = new List(); 
      listCustomer.Add(new Customer { name = "客户1", id = 0 }); 
      listCustomer.Add(new Customer { name = "客户2", id = 1 }); 
      listCustomer.Add(new Customer { name = "客户3", id = 5 }); 
      listCustomer.Add(new Customer { name = "客户4", id = 3 }); 
      listCustomer.Add(new Customer { name = "客户5", id = 4 }); 
      listCustomer.Add(new Customer { name = "客户6", id = 5 });
     
      ///升序 
      List listCustomer1 = listCustomer.OrderBy(s => s.id).ToList(); 
    
      //降序 
      List listCustomer2 = listCustomer.OrderByDescending(s => s.id).ToList(); 
    
      //Linq排序方式 
      List listCustomer3 = (from c in listCustomer 
    orderby c.id descending //ascending 
    select c).ToList(); 
    } 
    
    class Customer 
    { 
      public int id { get; set; } 
      public string name { get; set; } 
    } 
    
    		
  •  

    List排序实例四:使用orderby对整型字符串排序

     

  •  
  • C# 代码   复制
  • 
    static void Main()
    {
        OrdinalComparer comp = new OrdinalComparer();
    
        List<string> strs = new List<string>(){"11", "12", "1:"};
        foreach(string str in strs.OrderBy(n => n, comp))
            Console.writeLine(str);
    }
    
    public class OrdinalComparer: System.Collections.Generic.IComparer<String>
    {
        public int Compare(String x, String y)
        {
            return string.CompareOrdinal(x, y);
        }  
    }
    
    		
  •  

    标签:
    上一篇下一篇

    猜您喜欢

    热门推荐