[英]In C#, how can I get the top items that are properties of a list?
I have a project object which has a list of sponsors (which is an array of Person objects) as seen below 我有一个项目对象,其中有一个赞助者列表(是Person对象的数组),如下所示
var projectA = GetProject();
IEnumerable<Person> sponsors = projectA.Sponsors;
I now have list of these projects objects 我现在有这些项目对象的列表
List<Project> projects = GetProjects();
and I am trying to get the "top sponsors" for all projects 我正在努力争取所有项目的“顶级赞助商”
If a project had a single sponsor, I would do something like this: 如果一个项目只有一个赞助商,我会做这样的事情:
var topSponsors = projects.GroupBy(r->r.Sponsor).OrderByDescending(g->g.Count)
but in my case a project has multiple sponsors so I am looking for the right syntaxt that shows the top sponsors across this list of projects? 但就我而言,一个项目有多个赞助商,因此我正在寻找合适的语法,以显示此项目列表中的主要赞助商?
As an example, lets say 例如,假设
Project 1 ==> Sponsors (Tim, Joe) 项目1 ==>赞助商(蒂姆,乔)
Project 2 ==> Sponsors (Tim) 项目2 ==>赞助商(Tim)
Project 3 ==> Sponsors (Bill) 项目3 ==>赞助商(账单)
Project 4 ==> Sponsors (Tim, Joe) 项目4 ==>赞助者(蒂姆,乔)
I would want to order by: 我想按以下顺序订购:
Tim (3 projects) 蒂姆(3项目)
Joe (2 projects) 乔(2项目)
Bill (1 projects) 帐单(1个项目)
So you want the top n persons of all persons in the projects? 因此,您想要项目中所有人的前n位吗?
var top10Persons = projects
.SelectMany(p=> p.Sponsors)
.GroupBy(p => p)
.OrderByDescending(g => g.Count())
.Take(10)
.Select(g => g.First());
This presumes that Person
overrides Equals
+ GetHashCode
. 这假定
Person
重写Equals
+ GetHashCode
。 You could also provide a custom IEqualityComparer<Peerson>
for GroupBy.
您还可以为
GroupBy.
提供自定义IEqualityComparer<Peerson>
GroupBy.
If you also want the Count
of each person you could select an anonymos type: 如果您还想要每个人的
Count
,则可以选择匿名类型:
.....
.Take(10)
.Select(g => new { Count = g.Count(), Person = g.First() });
This should do the trick: 这应该可以解决问题:
var bestSponsors = projects.SelectMany(p => p.Sponsors)
.GroupBy(p => p.Name)
.OrderByDescending(g => g.ToList().Count)
.Select(p => new
{
Name = p.Key,
SponsoredProjectCount = p.ToList().Count
})
.ToList();
I am assuming you have a person class like this: 我假设您有一个人类:
public class Person
{
public string Name { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.