Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast IEnumerable<enum1> to List<enum2> convertation

Tags:

c#

ienumerable

I have two same enums that have the same names of members, but they are in different namespaces so they are "different types", but in fact namespace1.enum1 {a,b,c,d,e,f} and namespace2.enum2 {a,b,c,d,e,f}

How is the easiest way to convert IEnumerable<enum1> to List<enum2> without using loops?

like image 650
curiousity Avatar asked Dec 05 '16 12:12

curiousity


2 Answers

Well something's going to loop somewhere, but it doesn't have to be in your code. Just a LINQ Select will be fine:

var result = original.Select(x => (Enum2) x).ToList();
like image 158
Jon Skeet Avatar answered Nov 09 '22 15:11

Jon Skeet


Or you can use Cast (still O(n) :-))

var result = original.Cast<int>().Cast<Enum2>().ToList();

Warning It seems that this will not always work as expected (InvalidCastException can be thrown in some cases). See comments to figure out why.

like image 3
pwas Avatar answered Nov 09 '22 17:11

pwas