简体   繁体   中英

One-line converting Enum to Int array in C#

In trying to convert an enumeration into an int[] of its values, I initially came up with the long-winded:

Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope))
.Cast<Isolations.Enumerations.TypeSelectionScope>().Select(t => (int)t).ToArray()

It works, but.. well, it ain't pretty.

I did some searching, and found people using ConvertAll() for this purpose, over multiple lines. So I tried it inline.

Array.ConvertAll(Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope)), value => (int)value)

This generates a type error, and adding some casting within is going to make it as messy as the first attempt.

I also tried a direct cast to an int[] to no avail:

Enum.GetValues(typeof(Isolations.Enumerations.TypeSelectionScope)).Cast<int[]>()

Adding a ToArray() onto this fails also.

So, what's a single-line solution to this that isn't messy?

Enumerable.Cast<T> iterates through a collection and casts each item to T

You're trying to cast each instance to int[] - you want to cast them to int instead:

.Cast<int>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM