简体   繁体   English

将C#中的两个列表对象连接在一起

[英]Join together two list objects in C#

Basically, I'm coding a poker app and I have a class called Deck which is really just a List<> contain objects of the class Card . 基本上,我正在编写扑克应用程序,并且有一个名为Deck的类,它实际上只是一个List<>包含Card类。 It's literally just a list of cards. 它实际上只是一张卡片清单。

I'm now trying to concatenate two of these Decks together: playerCards and tableCards . 我现在正在尝试将其中两个Decks连接在一起: playerCardstableCards However, when I write this code, I get an error message: 但是,当我编写此代码时,出现错误消息:

playerCards.Concat(tableCards);

It tells me that "'Deck' does not contain a definition for 'Concat' and no extension method 'Concat' accepting a first argument of type 'Deck' could be found." 它告诉我,“'Deck'不包含'Concat'的定义,找不到可以接受类型为'Deck'的第一个参数的扩展方法'Concat'。”

How can I concatenate these two list objects together? 如何将这两个列表对象串联在一起?

Hopefully this explains Deck a bit better... 希望这可以更好地解释Deck ...

public class Deck
{

    public Deck()
    {
        deck = new List<Card>();
    }

    public List<Card> deck { get; }

The Concat method is an extension-method defined in Enumerable : Concat方法是在Enumerable定义的扩展方法:

IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second);

This means you can use it like this: 这意味着您可以像这样使用它:

IEnumerable<Card> deck1 = new List<Card>();
IEnumerable<Card> deck2 = new List<Card>();
IEnumerable<Card> deck3 = deck1.Concat(deck2);

It will return a new sequence of Card-objects. 它将返回一个新的Card对象序列。

The method AddRange is defined for fx List<T> : 为fx List<T>定义了方法AddRange

public void AddRange(IEnumerable<T> collection)

Use it like this: 像这样使用它:

List<Card> deck1 = new List<Card>();
List<Card> deck2 = new List<Card>();
deck2.AddRange(deck1);

This will modify the list deck1 by adding elements from deck2. 这将通过添加deck2中的元素来修改列表deck1。

So your choice of how to implement Concat or AddRange in your class Deck depends on which behaviour you want it to have: 因此,如何在类Deck实现ConcatAddRange的选择取决于您希望它具有的行为:

  • Return a new Deck containing cards from both Deck s 从两个Deck返回一个包含卡片的新Deck
  • Modify the Deck by adding cards from the other Deck 修改Deck从其他添加卡Deck

Perhaps you can use the following as inspiration: 也许您可以使用以下作为启发:

public class Deck
{
    private List<Card> cards;

    public IReadOnlyList<Card> Cards
    {
        get
        {
            return cards.AsReadOnly();
        }
    }

    public Deck()
    {
        cards = new List<Card>();
    }

    public Deck(IEnumerable<Card> cards)
    {
        cards = cards.ToList();
    }

    public Deck Concat(Deck other)
    {
        return new Deck(Cards.Concat(other.Cards));
    }

    public void AddRange(Deck other)
    {
        cards.AddRange(other.Cards);
    }
}
public void Concat(Deck other)
{
   this.deck.AddRange(other.deck);
}

Like this. 像这样。 List.AddRange List.AddRange

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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