Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

How to selectmany for enum?

$
0
0

Say for example I have this enum

public enum Suit
{
    Diamonds, Clubs, Hearts, Spades
}

How do I use LINQ selectmany to loop my enum four times?

This is version below is not in enum but my version, the Suit is enum

cards = new[] { "Spades", "Hearts", "Clubs", "Diamonds", }
                    .SelectMany(
                        suit => Enumerable.Range(1, 13),
                        (suit, rank) => new Card(rank, suit))
                    .ToArray();

I tried this but it says 'Cannot implicitly convert type 'Card[]' to 'System.Collections.Generic.List<Card>'

var suitAsList = Enum.GetValues(typeof(Suit)).Cast<Suit>().ToList();
        cards =
                suitAsList
                    .SelectMany(
                        suit => Enumerable.Range(1, 13),
                        (suit, rank) => new Card((Suit)suit, (Face)rank))
                    .ToArray();

My working version is below but wish to use LINQ selectmany method

        List<Card> coldDeck = new List<Card>(52);

        for (int j = 0; j < 4; j++)
            for (int i = 0; i < 13; i++)
                coldDeck.Add(new Card((Suit)j, (Face)i));
        cards = coldDeck;


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>