我有一个包含玩家编号的课程......
public class Game {
public int blackPlayer { get; set; }
public int whitePlayer { get; set; }
}
和......
List<Game> games;
我想知道哪个玩家编号在列表中出现次数最多(无论他们是扮演黑人还是白人)。有谁知道一个好的LINQ表达式吗?
答案 0 :(得分:5)
以下内容应该实现您的目标:
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);
答案 1 :(得分:1)
如果你想要所有的关系。
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();