Click here to Skip to main content
15,892,839 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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?
Posted
Updated 14-Aug-12 21:37pm
v2
Comments
StianSandberg 15-Aug-12 3:44am    
Tried AutoMapper ?

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.
 
Share this answer
 
v2
Comments
avi10788 21-Aug-12 8:36am    
Thnks Philip for your response..but i am not getting b1.b1field1 attribute, it gives properties of List.
Philip Stuyck 21-Aug-12 8:47am    
then you do this:
from B1 b1 in b1list
select new B2{b2field1=b1.b1field1,b2field2=b1.b1field2}
or post a code snippet of yours, because it should work the way it was
If the type B1 can be casted to B2, you may use Cast<B2>(), e.g.

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


Cheers
Andi
 
Share this answer
 
v3
Comments
avi10788 21-Aug-12 8:37am    
new List(list1.Cast<b2>());
gives build error as List expect a parameter.
Andreas Gieriet 21-Aug-12 9:52am    
Fixed: the list must have that <B2> too.
Thanks for pointing to this.

BTW: the Cast<B2>() is not even needed in .Net4:
list2 = new List<B2>(list1); is sufficient since the advent of co- and contra-variance support in C#.
Cheers
Andi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900