将匿名类型转换为类 [英] Convert anonymous type to class

查看:29
本文介绍了将匿名类型转换为类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 List anBook 中有一个匿名类型:

I got an anonymous type inside a List anBook:

var anBook=new []{

new {Code=10, Book ="Harry Potter"},
new {Code=11, Book="James Bond"}
};

是否可以将其转换为具有以下 clearBook 定义的列表:

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

public class ClearBook
{
  int Code;
  string Book; 
}

通过使用直接转换,即不循环遍历 anBook?

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

推荐答案

好吧,你可以使用:

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" }
};

您还可以通过反射来映射数据(可能使用 Expression 来编译和缓存策略),但这可能不值得.

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.

这篇关于将匿名类型转换为类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆