简体   繁体   中英

C# Count occurrences in list

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, Ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM