0

我有一个自定义Deck类,它继承了一个带有自定义类的 List Card

代码Deck

public class Deck : List<Card>
        {
            public void DrawCard(Deck d)
            {
                d.Add(this[0]);
                this.RemoveAt(0);
            }
            public Deck(bool deckHasCards)
            {
                if (deckHasCards)
                {
                    for (int i = 1; i <= 13; i++)
                    {
                        this.Add(new Card(i, Card.Suit.CLUBS));
                        this.Add(new Card(i, Card.Suit.DIAMONDS));
                        this.Add(new Card(i, Card.Suit.HEARTS));
                        this.Add(new Card(i, Card.Suit.SPADES));
                    }
                }
            }
            public void Shuffle()
            {
                Random rng = new Random();
                int n = this.Count;
                while (n > 1)
                {
                    n--;
                    int k = rng.Next(n + 1);
                    Card value = this[k];
                    this[k] = this[n];
                    this[n] = value;
                }
            }
        }

Card

public class Card
    {
        public Suit s { get; set; }
        public int num { get; set; }
        public enum Suit
        {
            HEARTS,
            DIAMONDS,
            CLUBS,
            SPADES
        }
        public Card(int number, Suit suit)
        {
            num = number;
            s = suit;
        }

        public override String ToString()
        {
            return num + " of " + s.ToString().ToLower();
        }
    }

一切都很好,但如果我想对一个Deck对象执行任何 LINQ 操作,我无法将它转换回Deck. 有没有(正确的)方法可以做到这一点?

4

1 回答 1

0

您可以将新的构造函数添加到Deck

public Deck(bool deckHasCards, IEnumerable<Card> cards)
{
    foreach (Card c in cards)
        this.Add(c);
}

并使用这样的行:

var deck = new Deck(deckHasCards: true, cards: deck.Where(card => card.num == 2));
于 2013-04-09T21:00:00.287 回答