Quickly convert IEnumerable <enum1> to list <enum2>
I have two identical enumerations that have the same member names, but they are in different namespaces, so they are "different types", but actually namespace1.enum1 {a, b, c, d, e, f} and namespace2.enum2 {a, b, c, d, e, f}
What is the easiest way to convert IEnumerable<enum1> to List<enum2> without using loops?
+7
curiousity
source share2 answers
Well, something is going to go in cycles somewhere, but it does not have to be in your code. Just LINQ Select will be fine:
var result = original.Select(x => (Enum2) x).ToList(); +14
Jon skeet
source shareOr you can use Cast (still O (n) :-))
var result = original.Cast<int>().Cast<Enum2>().ToList(); Caution It does not seem to always work as expected ( InvalidCastException may be thrown in some cases). See comments to find out why.
+3
pwas
source share