[英]How can I get the highest number in this Linq result?
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() };
}
Basically, player and computer combos have a keypair values of each number that appears and how many times it appears. 基本上,播放器和计算机组合具有出现的每个数字的密钥对值以及它出现的次数。
Here's the pickle. 这是泡菜。 I need to grab the number that appears the most from both collections.
我需要从两个集合中获取最多的数字。 If there are for example, two pairs (1,1 and 2,2) appearing in the computerCombos collection, I need to grab the combo with the highest number.
例如,如果有两对(1,1和2,2)出现在computerCombos集合中,我需要获取具有最高编号的组合。
Example: 例:
[1,1,2,4,5,6,7,7]
I need to get: 我需要得到:
7 appeared twice.
Notice how I didn't display 1, because 7 is of higher value. 请注意我没有显示1,因为7值更高。
Here my attempt, but it's not working as expected. 在这里我的尝试,但它没有按预期工作。 It fetches whatever the .First method gives.
它取得了.First方法给出的任何东西。
p 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!");
}
}
Thanks! 谢谢!
Try this: 试试这个:
var p = playerCombos.OrderByDescending(x => x.Count)
.ThenByDescending(x=>x.Key)
.First();
var c = computerCombos.OrderByDescending(x => x.Count)
.ThenByDescending(x=>x.Key)
.First();
This is more readable in query format actually: 实际上,这在查询格式中更具可读性:
var p = (from combo in playerCombos
orderby combo.Count descending, combo.Key descending
select combo).First();
Try: 尝试:
var p = playerCombos.Where(
x => x.Count ==
playerCombos.Max(y => y.Count)
).Max(x => x.Key)
Similar to Jon's answer, but to remove the nested operator I'd shift the calculation of the Max outside the where. 类似于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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.