简体   繁体   English

在C#中,如何按对象中的属性对集合进行排序?

[英]In C#, How can I sort a collection by a property in an object?

I have a collection of Person objects and a person can belong to many teams 我有一个Person对象的集合,一个人可以属于许多团队

public class Person
{
     public List<string> Teams();
} 

so I have a collection of these objects 所以我有这些对象的集合

List<Person> people = GetPeople();

Now given the collection I want to get the list of most used teams 现在给出集合,我想获得最常用的团队的列表

I can get a full list of all teams by doing this: 通过执行以下操作,我可以获得所有团队的完整列​​表:

   var teams = people.SelectMany(r=>r.Teams);

or I can get a distinct list of teams by doing this: 或者通过执行以下操作,我可以获得一组不同的团队:

   var teams = people.SelectMany(r=>r.Teams).Distinct(new TeamComparer());

but I now want to get the top 10 teams. 但我现在想获得前10名球队。

What is the correct way to sort teams by the most used? 用最常用的方式对团队进行排序的正确方法是什么? So for example if I have 例如,如果我有

  var person = new Person(){Teams = new List<string>{"Team A", "Team D"} }
  var person2 = new Person(){Teams = new List<string>{"Team B", "Team C"} }
  var person3 = new Person(){Teams = new List<string>{"Team B", "Team C"} }
  var person4 = new Person(){Teams = new List<string>{"Team B", "Team D"} }

so in the example above, it would return in order: 因此在上面的示例中,它将按顺序返回:

Team B B队
Team C C队
Team D D队
Team A A队

If you want to get ten teams with the highest usage count, you should group them, rather than eliminating the duplicates using Distinct() . 如果要让十支团队使用率最高,则应该将它们分组,而不是使用Distinct()消除重复项。 Once you have your groups, sort by group count, and take the first ten, like this: 分组后,按分组数排序,然后取前十个,如下所示:

var topTen = people
    .SelectMany(r => r.Teams)          // Get the teams with duplicates
    .GroupBy(t => t)                   // Group by team
    .OrderByDescending(g => g.Count()) // Sort by count
    .Take(10)                          // Take top ten
    .Select(g => g.Key)                // Drop groups
    .ToList();                         // Make a list
List<Person> lstpeople = GetPeople();
lstPerson = lstPerson.OrderBy(x => x.personID).toList();
lstPerson = lstPerson.orderbydescending(x => x.personID).toList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM