tags:

views:

1903

answers:

2

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?

+5  A: 

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. Oobviously 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.

Marc Gravell
+2  A: 

As Marc says, it can be done with reflection and expression trees... and as luck would have it, there's a class in MiscUtil which does exactly that. However, looking at your question more closely it sounds like you want to apply this conversion to a collection (array, list or whatever) without looping. That can't possibly work. You're converting from one type to another - it's not like you can use a reference to the anonymous type as if it's a reference to ClearBook.

To give an example of how the PropertyCopy class works though, you'd just need:

var books = anBook.Select(book => PropertyCopy<ClearBook>.CopyFrom(book))
                                 .ToList();
Jon Skeet
Can't the CLR infer the type and the property name and do the automatic conversion? .Net 4.0 should improve on this
Ngu Soon Hui
So that I don't have have to declare the type myself.
Ngu Soon Hui
I can't say I've seen much demand for this, and if feels like a bad idea generally.
Jon Skeet