[英]How to find how many times the same object appears in a list and then find a property of the most appeared object
我正在為一些編程實踐做一個撲克手評估器,我已經提交給codereview堆棧交換。 我需要能夠正確地比較雙手,為此我需要看到對的價值。 我目前檢查雙手班
private static PokerHandsRank CheckHandForPairs(Hand hand)
{
var faceCount = (from card in hand.Cards
group card by card.Face
into g
let count = g.Count()
orderby count descending
select count).Take(2).ToList(); // take two to check if multiple pairs of pairs, if second in list is 1 there will be two pairs
switch (faceCount[0])
{
case 1: return PokerHandsRank.HighCard;
case 2: return faceCount[1] == 1 ? PokerHandsRank.Pair : PokerHandsRank.TwoPair;
case 3: return faceCount[1] == 1 ? PokerHandsRank.ThreeOfKind : PokerHandsRank.FullHouse;
case 4: return PokerHandsRank.FourOfKind;
default: throw new Exception("something went wrong here");
}
}
正如你所看到的,我已經使用linq來獲得最多出現配對的列表,但是我不知道如何在我將它們分開后完成它以獲得卡的面值。
這是我目前的比較方法
public int CompareTo(Hand other)
{
if (HandRank == other.HandRank) //if the hand rank is equal, sort the cards by face value and compare the two biggest
{
sortHandbyFace(this); // sorts cards into order by face
sortHandbyFace(other);
for (int i = 4; 0 <= i; i--)
{
if (Cards[i].Face == other.Cards[i].Face)
{
if (i == 0) return 0;
continue;
}
return Cards[i].Face > other.Cards[i].Face ? 1 : -1;
}
}
return HandRank > other.HandRank ? 1 : -1;
比較完美的比較高卡問題,但我需要添加一個檢查,如果兩個手牌等級,然后檢查他們的價值是一對,兩對,滿屋或三種(然后找到最高的面值的一對)
如果您需要有關我的程序的更多信息,請隨時查看我的codereview帖子https://codereview.stackexchange.com/questions/152857/beginnings-of-a-poker-hand-classifier-part-2?noredirect=1&lq=1
這可能不是您正在尋找的,因為您正在比較object
而不僅僅是int
,但這可以幫助您開始。 基於這個問題: 如何獲得存儲在C#列表中的元素的頻率 。
using System.Linq;
List<int> ids = //
int maxFrequency = 0;
int IDOfMax = 0;
foreach(var grp in ids.GroupBy(i => i))
{
if (grp.Count() > maxFrequency)
{
maxFrequency = grp.Count();
IDOfMax = grp.Key;
}
}
// The object (int in this case) that appears most frequently
// can be identified with grp.key
更新:在重新閱讀問題之后 ,聽起來您需要嘗試使用查詢中的計數和面值返回一個新對象。
你可以這樣做:
public class FaceCountResult
{
public int Count { get; set; }
public Face FaceValue { get; set; }
public FaceCountResult(int count, Face faceValue)
{
Count = count;
FaceValue = faceValue;
}
}
然后, faceCount
應該看起來像這樣:
var faceCount = (from card in hand.Cards
group card by card.Face
into g
let count = g.Count()
orderby count descending
select new FaceCountResult(count, card.Face);
我不確定Take(2)
部分將如何考慮到這一點,因為我不太了解代碼的這一部分。
然后,你可以做一個switch
上faceCount[0].Count
,並使用faceCount[0].FaceValue
獲得面值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.