tags:

views:

58

answers:

2

I have a class that contains player numbers...

public class Game {
    public int blackPlayer { get; set; }
    public int whitePlayer { get; set; }
}

and a...

List<Game> games;

I want to know which player number occurs the most in the list (regardless if they played as black or white). Does anyone know a good LINQ expression this?

+5  A: 

The following should accomplish your goal:

var q = (from g in games
        from p in new[] {g.blackPlayer, g.whitePlayer}
        group p by p into pgroup
        orderby pgroup.Count() descending
        select new { Player = pgroup.Key,  Count =  pgroup.Count() }).FirstOrDefault();


Console.WriteLine("Player # {0} played {1} times which is the most", q.Player,  q.Count);
Matthew Manela
+1  A: 

If you want all the ties.

List<int> mostFrequentPlayers = games.Select(g => g.blackPlayer)
  .Concat(games.Select(g => g.whitePlayer))
  .GroupBy(p => p) //into g
  .GroupBy(g => g.Count()) //into g2
  .OrderByDescending(g2 => g2.Key)
  .First()
  .SelectMany(g2 => g2, g => g.Key) //unpack g2 as g.Key
  .ToList();
David B