Zetland
Zetland

Reputation: 567

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; }

Upvotes: 0

Views: 4582

Answers (2)

Daniel Brixen
Daniel Brixen

Reputation: 1663

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 Decks
  • 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);
    }
}

Upvotes: 3

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

Like this. List.AddRange

Upvotes: 1

Related Questions