转换匿名类型上课 [英] Convert Anonymous Type to Class

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

问题描述

我有一个列表里面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();

但没有,没有直接的转换支持。 Oobviously你需要添加访问等(不要使公共领域) - 我猜:

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

也有事情可以做与反射映射数据(可能使用防爆pression 来编译和缓存策略),但它可能ISN T值得的。

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天全站免登陆