I have 2 Lists, one for Players and another for Coaches.
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. Thank you in advance!
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? 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...
See more on this question at Stackoverflow