[英]How to use Linq instead of foreach to Group and Count
I have 2 Lists, one for Players and another for Coaches. 我有2个列表,一个用于播放器,另一个用于教练。
To count number of Players belong to a Coach, I used: 为了计算属于一名教练的球员人数,我使用了:
var g = AllePlayer.GroupBy(play=> play.coachNumer);
foreach (var grp in g)
{
foreach (Coach co in AlleCoaches)
{
if (co.coachNumer== grp.Key)
{
co.NumOfPlayer= grp.Count();
}
}
}
Now I want to know if there is a nice way to put the lover parts with "foreach" in a nice Linq syntax to avoid this "foreach" loops. 现在,我想知道是否存在一种很好的方法,可以将带有“ foreach”的情人部分放入一种不错的Linq语法中,以避免这种“ foreach”循环。 Thank you in advance!
先感谢您!
You could change the statement around a little bit. 您可以稍微更改一下语句。 Since ultimately you want to change a property on each coach, it's easiest to loop through that list, as in:
由于最终您想更改每个教练的属性,因此最容易遍历该列表,如下所示:
foreach (Coach co in AlleCoaches)
{
co.NumOfPlayer= AllePlayer.Where(p => p.coachNumber == co.coachNumber)
.Count();
}
This would be a simpler approach: 这将是一个更简单的方法:
var query = AllePlayer.GroupBy(player => player.coachNumer,
(coach, players => new {
Coach = coach,
Count = players.Count() }));
That will give you a sequence where each element is the coach and the number of players for that coach. 这将为您提供一个序列,其中每个元素都是教练以及该教练的球员人数。
Then you could iterate over the result, and assign the value into Coach.NumOfPlayer
, but do you really need to? 然后,您可以遍历结果,并将值分配给
Coach.NumOfPlayer
,但是您真的需要吗? If you do, this will do it: 如果您这样做,则可以这样做:
foreach (var pair in query)
{
pair.Coach.NumOfPlayer = pair.Count;
}
Personally it doesn't feel like "number of players" should be part of the Coach
type to start with... 就个人而言,从“开始”的角度来看,“球员数量”应该不是
Coach
一部分。
AlleCoaches.ToList()
.ForEach(n=>n.NumOfPlayer=AllePlayer.Where(n=>coachNumer==n.coachNumer).Count());
var g = AllePlayer.TakeWhile(play=> ( play.coachNumer!=null));
您可以采用所需的任何逻辑,但是语法相同。
var count = g.Count();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.