Convert anonymous type to class

后端 未结 3 494
不知归路
不知归路 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:29

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

提交回复
热议问题