LINQ with two lists predicate?

402 views Asked by At

I've got a code like this:

string[] teamNames = teams.Select(x => x.Name).ToArray();
List<int> wins = new List<int>();
foreach(var _team in teamNames)
{
    wins.Add(matches.Count(x => 
        ((x.Team1 == _team && x.Maps.Count(map => map.Score1 > map.Score2) > x.Maps.Count(map => map.Score2 > map.Score1)) || 
        (x.Team2 == _team && x.Maps.Count(map => map.Score2 > map.Score1) > x.Maps.Count(map => map.Score1 > map.Score2))
        )));
}

I was wondering if you could somehow count the wins for each team without the foreach first which just yields team name after team name. Any ideas for that/

2

There are 2 answers

10
Sergey Kalinichenko On BEST ANSWER

You should be able to do it by replacing the foreach with a Select:

var wins = teamNames
    .Select(_team =>
        matches.Count(x => 
        ((x.Team1 == _team && x.Maps.Count(map => map.Score1 > map.Score2) > x.Maps.Count(map => map.Score2 > map.Score1)) || 
        (x.Team2 == _team && x.Maps.Count(map => map.Score2 > map.Score1) > x.Maps.Count(map => map.Score1 > map.Score2))
        ))
    )
.ToArray();
0
Nader On

You can also use groupby directly on the matches without creating the teamNames.