Simon Van Duffelen
Simon Van Duffelen

Reputation: 41

How to Instantiate a List with a List of new objects

The following code works.

List<Card> Cards = new List<Card>()
{
    new Card("SA"), 
    new Card("HA"), 
    new Card("CA"), 
    new Card("DA"), 
    new Card("SK"), 
    new Card("S2"), 
    new Card("D2") 
};

I would like to reduce the clutter so I'm looking for some thing like this

List<Card> Cards = new List<Card>() 
{ 
    new Card() 
    { 
        "SA", "HA", "CA", "DA", "SK", "S2", "D2"
    }
};

I swear. I saw it somewhere but I just can't define it properly to google the answer.

Upvotes: 3

Views: 152

Answers (4)

Iliar Turdushev
Iliar Turdushev

Reputation: 5213

In C# 6 you can use Extension Add methods in collection initializers:

public static class CardListExtensions
{
   public static void Add(this List<Card> list, string name)
   {
      list.Add(new Card(name));
   }
}

After adding such extension method you will be able to use it in collection initializer:

List<Card> list = new List<Card> {"SA", "HA", "CA"};

Upvotes: 3

weichch
weichch

Reputation: 10035

Just to extend answers from others

If Card class has a type conversion operator like this:

class Card
{
    public Card(string str)
    { }

    // This one converts string to Card.
    public static implicit operator Card(string str)
    {
        return new Card(str);
    }
}

Then you could do the following which looks close to what you got in question:

var list = new List<Card> { "SA", "HA", "CA", "DA", "SK", "S2", "D2" };

Upvotes: 5

Alex - Tin Le
Alex - Tin Le

Reputation: 2000

If you are looking for a shorter code, how about this

"SA_HA_CA_DA_SK_S2_D2".Split("_").Select(x => new Card(x)).ToList();

Upvotes: -1

John Wu
John Wu

Reputation: 52210

You could try this:

var codes = new string [] { "SA", "HA", "CA", "DA", "SK", "S2", "D2" };
var cards = codes.Select( code => new Card(code) ).ToList();

Upvotes: 7

Related Questions