Convert anonymous type to class

后端 未结 3 489
不知归路
不知归路 2020-11-29 04:41

I got an anonymous type inside a List anBook:

var anBook=new []{

new {Code=10, Book =\"Harry Potter\"},
new {Code=11, Book=\"James Bond\"}
};
3条回答
  •  日久生厌
    2020-11-29 05:25

    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.CopyFrom(book))
                                     .ToList();
    

提交回复
热议问题