LINQ:按组计数收集订单

时间:2015-02-23 14:40:47

标签: c# linq count

假设我有一组Person对象,每个人都有一个头发颜色属性(值为:Blonde,Black,Brown,Red,White)。

如何使用LINQ根据组计数重新排序这些Person对象(按降序排列)?

示例:

鲍勃(布朗),杰克(金发),马克(布朗),比尔(怀特),乔治(布朗),吉姆(金发),托马斯(红色)

应该重新订购:

鲍勃(布朗),马克(布朗),乔治(布朗),杰克(金发),吉姆(金发),比尔(白人),托马斯(红色)

性能也是一个关键问题,因此最少的代码行将更为可取。

1 个答案:

答案 0 :(得分:1)

也许这有效:

List<Person> persons =
    new List<Person>() {
    new Person("Bob", "Brown"),
    new Person("Jack", "Blonde"),
    new Person("Mark", "Brown"),
    new Person("Bill", "White"),
    new Person("George", "Brown"),
    new Person("Jim", "Blonde"),
    new Person("Thomas", "Red")
};

foreach (var a in persons.GroupBy(p => p.HairColor).OrderByDescending(g => g.Count()).SelectMany(g => g)) {
    Console.WriteLine(a);
}

WHERE ...

public class Person {
    public Person(string name, string hairColor) {
        Name = name;
        HairColor = hairColor;
    }
    public string Name { get; set; }
    public string HairColor { get; set; }

    public override string ToString() {
        return Name + " (" + HairColor + ")";
    }
}