如何使用Linq维护列表顺序时进行排序和分组

时间:2012-03-04 06:37:34

标签: c# linq

如何使用Linq对以下人员列表进行排序,以便按ID分组,并保证维护它们的顺序。

List<person>people = new List<person>(); 
people.Add(new Person(1, "joe"));
people.Add(new Person(1, "john"));
people.Add(new Person(2, "bob"));
people.Add(new Person(3, "tracy"));
people.Add(new Person(2, "harry"));
people.Add(new Person(1, "ellen")); 
people.Add(new Person(3, "mary"));

我想要的结果:

Person(1, "joe")
Person(1, "john")
Person(1, "ellen")
Person(2, "bob")
Person(2, "harry")
Person(3, "tracy")
Person(3, "mary")

3 个答案:

答案 0 :(得分:2)

这就足够了:

var orderedPeople = people.OrderBy(p => p.Id).ToList();

Enumerable.OrderBy执行稳定的排序:

  

此方法执行稳定排序;也就是说,如果两个键   元素相等,元素的顺序被保留。

List<T>guarantee that items will be returned in the order they were added。所以你会得到你想要的结果:

Person(1, "joe")
Person(1, "john")
Person(1, "ellen")
Person(2, "bob")
Person(2, "harry")
Person(3, "tracy")
Person(3, "mary")

答案 1 :(得分:1)

    var result = people.Select((person,index)=>new{person,index})
      .OrderBy(pair => pair.person.ID)
      .ThenBy(pair => pair.index)
      .Select(pair => pair.person)
      .ToArray();

答案 2 :(得分:0)

您可以按照以下方式使用LINQ订购此列表.....

var orderedList = from p in people
                   orderby p.Id ascending
                   select p;