7

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?

RPichioli
  • 3,245
  • 2
  • 25
  • 29
curiousity
  • 4,703
  • 8
  • 39
  • 59
  • 2
    There isn't a *safe* way of doing this without loops, but if you're able to use `unsafe` code, you can transmute the memory directly via a cast. This might result in invalid memory, if the enums have different memory layouts, though. – This company is turning evil. Dec 05 '16 at 12:59

2 Answers2

14

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();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

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.

pwas
  • 3,225
  • 18
  • 40
  • That will actually throw an exception in some cases due to an inappropriate optimization that `Cast` makes. Bizarre, but true. There's another post about it somewhere - will try to dig it up. – Jon Skeet Dec 05 '16 at 12:56
  • See http://stackoverflow.com/questions/40604183/ (The `int`/`uint` is like `int`/enum.) – Jon Skeet Dec 05 '16 at 12:58
  • 1
    @JonSkeet If the underlying type for both enums is the same then would that still be an issue here? Though it's probably worth avoiding this just because of the boxing. – juharr Dec 05 '16 at 12:58
  • 1
    @JonSkeet hmm, nice issue. I'll leave the answer for future readers. – pwas Dec 05 '16 at 13:00