Miguel Moura
Miguel Moura

Reputation: 39364

Enum to Class with lambda expression

I have an Enum and a Class:

public enum Colors { Red = 1, Yellow = 2 }

public class Color {
  public int Value { get; set; }
  public string Name { get; set; }
}

Can I create a List from the enum Colors values using a lambda expression?

Thank you, Miguel

Upvotes: 1

Views: 7972

Answers (4)

Nicholas Carey
Nicholas Carey

Reputation: 74227

Theres at least two ways to do it (though I can't imagine why you'd need to):

static void Main( string[] args )
{
  List<Color> colorList1 = Enum.GetValues(typeof(Colors)).Cast<Colors>().Select( c => new Color( c.ToString(), (int)c ) ).ToList() ;
  List<Color> colorList2 = Enum.GetNames(typeof(Colors)).Zip( Enum.GetValues(typeof(Colors)).Cast<int>() , (n,v)=> new Color(n,v)).ToList() ;
  return ;
}
class Color
{
  public Color( string name , int value )
  {
    Name = name ;
    Value = value ;
  }
  public string Name { get ; set ;  }
  public int    Value { get ; set ; }
  public override string ToString()
  {
    return string.Format( "{0}:{1}" , Name , Value ) ;
  }
}
enum Colors
{
  Red    = 1 ,
  Orange = 2 ,
  Yellow = 3 ,
  Green  = 4 ,
  Blue   = 5 ,
  Indigo = 6 ,
  Violet = 7 ,
}

Upvotes: 1

Moho
Moho

Reputation: 16498

Assumes you meant for the Name property to be a string instead of an int

( ( IEnumerable<int> )Enum.GetValues(typeof(Colors)) )
    .Select(ev =>
    new Color()
    {
        Value = ev,
        Name = Enum.GetName(typeof(Colors), ev)
    })
    .ToList();

Upvotes: 6

Grant Winney
Grant Winney

Reputation: 66439

This will give you a list of the enum values. You don't need to create a custom Color class.

var myColorsList = Enum.GetValues(typeof (Colors)).Cast<Colors>().ToList();

If you really want to use your Color object:

var myColors = Enum.GetValues(typeof (Colors)).Cast<Colors>()
                   .Select(x => new Color{Value = (int)x, Name = x.ToString()})
                   .ToList();

Upvotes: 1

dkackman
dkackman

Reputation: 15549

First change the Name property to a string and then try this:

public enum Colors { Red = 1, Yellow = 2 }

public class Color
{
    public int Value { get; set; }
    public string Name { get; set; }
}

static void Main(string[] args)
{
    var colorClasses = from name in Enum.GetNames(typeof(Colors))
                       select
                       new Color()
                       {
                           Value = (int)Enum.Parse(typeof(Colors), name),
                           Name = name
                       };
}

Upvotes: 1

Related Questions