基本上,我有一个小程序,我想在其中对对象列表执行一系列排序。每个排序都应该对对象的不同属性进行操作,并遵循上一个排序产生的顺序
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乔治16林戈22乔治27约翰32Paul 38约翰43Paul 43乔治51Paul 64Ringo 73John 80
但我希望它能产生这个输出:
乔治16乔治27乔治51约翰32约翰43约翰80Paul 38Paul 43Paul 64Ringo 5林戈22Ringo 73
换句话说,我希望它按Name
排序,然后在每个Name
"组"内按Age
执行本地化排序。显然,到目前为止,我使用的Sort()
方法并没有做到这一点,它只是执行两个链式的OrderBy
。
使用IEnumerable
可以做到这一点的最佳方法是什么?理想情况下,我希望该解决方案能够扩展和支持我想要的任意多个链式排序,每个排序都会产生一组"组",下一个排序器必须将其排序本地化到这些"组"。
尝试使用它应该在不破坏第一个订单的情况下重新排序
http://msdn.microsoft.com/en-us/library/bb534743.aspx
return people.OrderBy(p => p.Name).ThenBy(p => p.Age);