How can I use Cast() Extension method for above conversion?
e.g.
var aType = anonymousType;
IEnumreable<MyType> = aType.Cast();
Solved By
aType.Select(i => new MyType { } ).ToList();
The only type that you can cast an anonymous type to is Object. If you want any other type, you have to create those objects from the data in the anonymously typed objects.
Example:
List<MyType> items = aType.Select(t => new MyType(t.Some, t.Other)).ToList();
You should consider to create the MyType objects already when you get the data, instead of creating anonymously typed objects.
Is aType is an IEnumerable<anonymous type> returned by e.g. a linq query?
You might want to use Select (which applies a transformation function to an element) insted of Cast which just performs a cast.
IEnumerable<MyType> = aCollection.Select(e => SomeExpressionWithE);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With