Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert Anonymous type to Ttype?

Tags:

c#

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();
like image 785
Vikas Avatar asked Dec 06 '22 06:12

Vikas


2 Answers

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.

like image 150
Guffa Avatar answered Dec 09 '22 16:12

Guffa


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);
like image 25
Dario Avatar answered Dec 09 '22 15:12

Dario