Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert anonymous type to class

I got an anonymous type inside a List anBook:

var anBook=new []{  new {Code=10, Book ="Harry Potter"}, new {Code=11, Book="James Bond"} }; 

Is to possible to convert it to a List with the following definition of clearBook:

public class ClearBook {   int Code;   string Book;  } 

by using direct conversion, i.e., without looping through anBook?

like image 328
Graviton Avatar asked Jan 15 '09 08:01

Graviton


People also ask

What is an anonymous class in C#?

In C#, an anonymous type is a type (class) without any name that can contain public read-only properties only. It cannot contain other members, such as fields, methods, events, etc. You create an anonymous type using the new operator with an object initializer syntax.

How do you define anonymous type?

Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.


Video Answer


1 Answers

Well, you could use:

var list = anBook.Select(x => new ClearBook {                Code = x.Code, Book = x.Book}).ToList(); 

but no, there is no direct conversion support. Obviously you'll need to add accessors, etc. (don't make the fields public) - I'd guess:

public int Code { get; set; } public string Book { get; set; } 

Of course, the other option is to start with the data how you want it:

var list = new List<ClearBook> {     new ClearBook { Code=10, Book="Harry Potter" },     new ClearBook { Code=11, Book="James Bond" } }; 

There are also things you could do to map the data with reflection (perhaps using an Expression to compile and cache the strategy), but it probably isn't worth it.

like image 189
Marc Gravell Avatar answered Oct 05 '22 16:10

Marc Gravell