从List(Generic1)的转换>使用C#列出(Generic2) [英] Conversion from List(Generic1)> to List(Generic2) using C#

查看:94
本文介绍了从List(Generic1)的转换>使用C#列出(Generic2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好..

我有两个实体B1和B2:

实体B1:
id
列出<B2>

实体B2:
名称

从linq查询中,我正在获取列表<B1>.我必须为数据源分配List<B2>
的值
基本上我想将列表<B1>转换为列表<B2>


Hi All..

I have two entity B1 and B2:

Entity B1:
id
List <B2>

Entity B2:
name

From the linq query i am getting the List <B1>. I have to assign a data source with the values of List <B2>

Basically i want to type cast the List <B1> into list <B2>


how can i achive this?

推荐答案

在linq中存在强制转换运算符,但是如果您尝试这样做,则会得到强制转换异常.如果这两个班级不在亲子关系中.
例如,如果B2是从B1派生的,并且您具有B1的列表,并且知道元素实际上是B2,则可以执行此强制转换.如果您有一个B2列表,则它隐含地已经是一个B1列表,因为B1是父级,在这种情况下,无需强制转换.

您需要执行的操作是:

来自b1list中的b1
选择新的B2(b1)

B2必须具有一个额外的构造函数,该构造函数可以从B1实例构造自身.
但是还有其他方法也可以执行此操作,而无需此构造函数.

来自b1list中的b1
选择新的B2 {b2field1 = b1.b1field1,b2field2 = b1.b1field2}

此过程称为投影.
There exists a cast operator in linq, but if you were to try this you would get a cast exception. if the two classes are not in a parent child relationsship.
For instance if B2 is derived from B1, and you have a list of B1 and you know that the elements are actually B2 then you can do this cast. If you have a B2 list, then it is implicitely already a B1 list because B1 is the parent and in that case there is no need to cast.

What you have to do is this:

from b1 in b1list
select new B2(b1)

B2 has to have an extra constructor where it is able to construct itself from a B1 instance.
But there are other ways to do this as well without the need for this constructor.

from b1 in b1list
select new B2{b2field1=b1.b1field1,b2field2=b1.b1field2}

this process is called projection.


如果可以将类型B1强制转换为B2,则可以使用Cast<B2>(),例如

If the type B1 can be casted to B2, you may use Cast<B2>(), e.g.

List<B1> list1 = ...;
List<B2> list2 = new List<B2>(list1.Cast<B2>());



干杯
安迪



Cheers
Andi


这篇关于从List(Generic1)的转换&gt;使用C#列出(Generic2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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