Reputation: 101
I have a type Card
with an int
property called Value
where Ace = 14, Five = 5, etc.
If I have a list of Cards (5), ie. a hand. What I would like to do is count the number cards where the Value
is equal to another card, I.e. Finding 4 of a kind, 3 of a kind, a pair, two pair etc. I'm fairly new to C#/programming, but I believe this is a case for LINQ/Lambda expression? Can someone help me out?
class Card : IComparable<Card>
{
private string name;
private int value;
private string suit;
public int Value
{
get
{
return value;
}
}
<.....>
//Constructor accepts string ex. "AH" and builds value 14, suit "Hearts"
public int CompareTo(Card that)
{
if (this.value > that.value) return -1;
if (this.value == that.value) return 0;
return 1;
}
}
List<Card> HandBuilder = new List<Card>();
HandBuilder.Add(...); //5 Cards
HandBuilder.Count ?? //Help
Upvotes: 2
Views: 9002
Reputation: 203802
It's pretty trivial using GroupBy
.
var cards = HandBuilder.GroupBy(card => card.Value)
.OrderByDescending(group => group.Count());
To check for four of a kind just see if the first group has four items; to check for three of a kind see if the first group has three items. To check for two pair just see if the first two groups each have two items.
Upvotes: 5