我有一个自定义Deck
类,它继承了一个带有自定义Card
类的List。
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
。有没有(正确的)方法去做这件事?
答案 0 :(得分: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));