Xåp*_* - 0 .net c# linq sorting
基本上,我有一个小程序,我想在一个对象列表上执行一系列排序.每种排序都应该在对象的不同属性上运行,并遵循前一种排序产生的排序.这是我到目前为止所拥有的:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:
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,然后Age在每个Name"组" 内执行本地化排序.显然,Sort()到目前为止我所使用的方法并没有这样做,它只执行两个链接OrderBy.
我能做到这一点的最佳方式是什么IEnumerable?理想情况下,我希望扩展和支持尽可能多的链式排序的解决方案,每种类型产生一组"组",下一个分类器必须将其排序本地化.
尝试使用它应重新排序而不破坏第一个订单
http://msdn.microsoft.com/en-us/library/bb534743.aspx
return people.OrderBy(p => p.Name).ThenBy(p => p.Age);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
207 次 |
| 最近记录: |