private static void VerifyWinner(int[] PlayerRolls, int[] ComputerRolls)
{
var playerCombos = from number in PlayerRolls
group number by number into n
where n.Count() > 1
select new { n.Key, Count = n.Count() };
var computerCombos = from number in ComputerRolls
group number by number into n
where n.Count() > 1
select new { n.Key, Count = n.Count() };
}
基本上,玩家和计算机组合具有每个出现的数字的密钥对值以及它出现的次数。
这是泡菜。我需要从两个集合中获取最多的数字。例如,如果有两对(1,1和2,2)出现在computerCombos集合中,我需要获取具有最高编号的组合。
示例:
[1,1,2,4,5,6,7,7]
我需要得到:
7 appeared twice.
注意我没有显示1,因为7的值更高。
这是我的尝试,但它没有按预期工作。它取出了.First方法给出的任何东西。
P
rivate static void VerifyWinner(int[] PlayerRolls, int[] ComputerRolls)
{
var playerCombos = from number in PlayerRolls
group number by number into n
where n.Count() > 1
select new { n.Key, Count = n.Count() };
var computerCombos = from number in ComputerRolls
group number by number into n
where n.Count() > 1
select new { n.Key, Count = n.Count() };
var p = playerCombos.First();
var c = computerCombos.First();
if (p.Count > c.Count)
{
Console.WriteLine("Player wins with a {0} card combo!", p.Count);
}
else if (p.Count < c.Count)
{
Console.WriteLine("Computer wins with a {0} card combo!", c.Count);
}
else
{
Console.WriteLine("The match was a draw!");
}
}
谢谢!
答案 0 :(得分:3)
试试这个:
var p = playerCombos.OrderByDescending(x => x.Count)
.ThenByDescending(x=>x.Key)
.First();
var c = computerCombos.OrderByDescending(x => x.Count)
.ThenByDescending(x=>x.Key)
.First();
实际上,这在查询格式中更具可读性:
var p = (from combo in playerCombos
orderby combo.Count descending, combo.Key descending
select combo).First();
答案 1 :(得分:1)
尝试:
var p = playerCombos.Where(
x => x.Count ==
playerCombos.Max(y => y.Count)
).Max(x => x.Key)
答案 2 :(得分:0)
与Jon的答案类似,但是要删除嵌套的运算符,我会将Max的计算移到where之外。
var comboMax = (from combo in playerCombos
let max = playerCombos.Max(c => c.Count)
where combo.Count == max
select combo)
.Max(combo => combo.Key);