Jon
Jon

Reputation: 40062

Get int values of Enum[]

I have a method such as:

public void DoIt(params MyEnum[] channels)
{

}

Is there a way to get the int values of the enums in the params?

I tried var myInts = channels.Select(x => x.Value) but no luck

Upvotes: 2

Views: 240

Answers (7)

Zakharia Stanley
Zakharia Stanley

Reputation: 1

var ints = (int[]) (object) channels;

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245479

var myInts = channels.Cast<int>();

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1063964

Another way to do the same, without LINQ:

var vals = Array.ConvertAll(channels, c =>(int)c);

Upvotes: 5

evanmcdonnal
evanmcdonnal

Reputation: 48124

var myInts = channels.Select(x=x.Value) this doesn't work because = needs to be => (int)x

I think var myInts = channels.Select(x => (int)x).ToArray(); will do what you want.

Upvotes: 2

Mike Christensen
Mike Christensen

Reputation: 91696

You could do:

var myInts = channels.Select(e => (int)e);

Or as a LINQ query:

var myInts = from e in channels select (int)e;

You could then call ToArray() or ToList() on myInts to get a MyEnum[] or a List<MyEnum>

Upvotes: 1

gideon
gideon

Reputation: 19465

This should do it:

public void DoIt(params MyEnum[] channels)
{
   int[] ret = channels.Select(x => ((int)x)).ToArray();
}

Upvotes: 1

Matten
Matten

Reputation: 17603

You can do a cast in the select clause:

var myInts = channels.Select(x => (int)x);

Upvotes: 5

Related Questions