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, losers and computer combos have key pair values ​​for each number that appears and how many times it appears.

Here's the pickle. I need to capture the number that is most similar to both collections. If there are, for example, two pairs (1,1 and 2,2) appearing in the computerCombos collection, I need to capture the combos with the highest number.

Example:

 [1,1,2,4,5,6,7,7] 

I need to get:

 7 appeared twice. 

Please note that I did not show 1, because 7 has a higher value.

Here is my attempt, but it does not work as expected. It extracts everything that the first method gives.

R

 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!

+4
source share
3 answers

Try the following:

  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 most readable in the request format:

 var p = (from combo in playerCombos orderby combo.Count descending, combo.Key descending select combo).First(); 
+3
source

Try:

  var p = playerCombos.Where( x => x.Count == playerCombos.Max(y => y.Count) ).Max(x => x.Key) 
+1
source

As John answers, but to remove the nested statement, I would shift the calculation of Max out of that place.

 var comboMax = (from combo in playerCombos let max = playerCombos.Max(c => c.Count) where combo.Count == max select combo) .Max(combo => combo.Key); 
0
source

Source: https://habr.com/ru/post/1343088/


All Articles