2013-02-09 88 views
0

基本上,我有一個小程序,我想在對象列表上執行一系列排序。每種排序都應該在對象的不同屬性上進行操作,並遵守前一種排序所產生的排序。這是我到目前爲止有:如何使用IEnumerable連接分揀機,每臺分揀機都遵守上一次生產的順序?

class Program 
{ 
    static void Main(string[] args) 
    { 
     List<Person> people = new List<Person>(); 
     people.Add(new Person { Name = "John", Age = 43 }); 
     people.Add(new Person { Name = "Ringo", Age = 73 }); 
     people.Add(new Person { Name = "John", Age = 32 }); 
     people.Add(new Person { Name = "Paul", Age = 38 }); 
     people.Add(new Person { Name = "George", Age = 16 }); 
     people.Add(new Person { Name = "John", Age = 80 }); 
     people.Add(new Person { Name = "Ringo", Age = 22 }); 
     people.Add(new Person { Name = "Paul", Age = 64 }); 
     people.Add(new Person { Name = "George", Age = 51 }); 
     people.Add(new Person { Name = "George", Age = 27 }); 
     people.Add(new Person { Name = "Ringo", Age = 5 }); 
     people.Add(new Person { Name = "Paul", Age = 43 }); 

     Print(Sort(people)); 
    } 

    static IEnumerable<Person> Sort(IEnumerable<Person> people) 
    { 
     //order by name first, then order by age 
     return people.OrderBy(p => p.Name).OrderBy(p => p.Age); 
    } 

    static void Print(IEnumerable<Person> people) 
    { 
     foreach (Person p in people) 
      Console.WriteLine("{0} {1}", p.Name, p.Age); 
    } 

    class Person 
    { 
     public string Name {get; set;} 

     public int Age { get; set; } 
    } 
} 

這將產生以下的輸出:

Ringo 5 
George 16 
Ringo 22 
George 27 
John 32 
Paul 38 
John 43 
Paul 43 
George 51 
Paul 64 
Ringo 73 
John 80

但我想它產生這個輸出:

George 16 
George 27 
George 51 
John 32 
John 43 
John 80 
Paul 38 
Paul 43 
Paul 64 
Ringo 5 
Ringo 22 
Ringo 73

換句話說,我想要它通過Name訂購,然後在每個Name內執行Age的本地訂購「組」。很顯然,我迄今爲止的方法並沒有這樣做,它只是執行兩個鏈接OrderBy's。

我可以用IEnumerable做這件事的最佳方式是什麼?理想情況下,我希望解決方案能夠根據需要擴展和支持儘可能多的鏈接排序,每種排序都會生成一組「分組」,以便下一個分揀程序必須對其排序進行本地化。

+4

你看着ThenBy()做鏈接? – Jay 2013-02-09 20:30:24

+1

你應該像上面提到的那樣使用'ThenBy',但如果你感興趣的話:你有沒有注意到這兩位43歲的孩子是按字母順序排列的?這可能只是一個巧合,但事實並非如此。這是因爲'Enumerable.OrderBy'執行一個穩定的排序,這意味着任何兩個相同年齡的記錄按照它們出現在底層枚舉中的順序進行排序,該枚舉按名稱排序。這導致了另一種解決方案:'.OrderBy(p => p.Age).OrderBy(p => p.Name)'。 – hvd 2013-02-09 21:47:05

回答