简体   繁体   中英

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 . It's literally just a list of cards.

I'm now trying to concatenate two of these Decks together: playerCards and tableCards . 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."

How can I concatenate these two list objects together?

Hopefully this explains Deck a bit better...

public class Deck
{

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

    public List<Card> deck { get; }

The Concat method is an extension-method defined in 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.

The method AddRange is defined for fx List<T> :

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.

So your choice of how to implement Concat or AddRange in your class Deck depends on which behaviour you want it to have:

  • Return a new Deck containing cards from both Deck s
  • Modify the Deck by adding cards from the other 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

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