Idan Hazan
Idan Hazan

Reputation: 149

linq orderby with some condition

I'm trying to sorting groups by active players...

In this case, the first group contains the biggest players inside:

List<Group> groups = tournament.Groups.OrderByDescending(o => o.Players.Count).ToList();

I have to add an filter that will count only active players, Something like this:

if (o.Players[index].Active == true)
    count Players[index] into o.Players.Count

Can someone help me with the syntax?

Upvotes: 0

Views: 78

Answers (3)

usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26924

You may like to show in the result how many actual players are, not only sorting by them

var query = from g in tournament.Groups
            let activePlayers = g.Players.Count(p=>p.Active)

            orderby activePlayers descending
            select new {Group = g, ActivePlayers = activePlayers};

Upvotes: 0

Kahbazi
Kahbazi

Reputation: 15015

you can use this :

List<Group> groups = tournament.Groups
                    .OrderByDescending(o => o.Players.Count(P => P.Active)).ToList();

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 157136

If you want to filter on active players only, you can hand over a predicate in the Count extension method:

List<Group> groups = tournament
                     .Groups
                     .OrderByDescending
                         (o => o.Players.Count(p => p.Active))
                     .ToList();

Upvotes: 1

Related Questions