I'm having some basic problem with linq, I tried to google but didn't get the desired reuslt.
Lets say We have two class with almost similar signature like these:
public class A
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
}
public class B
{
public int x { get; set; }
public int y { get; set; }
public int z { get; set; }
}
Here A is data context class which is generated by the framework while creating the .edmx file & B is my custom class to carry data to UI. I'm querying the data base using A & getting a iqueryable list. Now I need to convert this list into another list of type B. How can I do that?
You need to use Select
to project from one type to another, then ToList
to create a list:
// Property names changed to follow .NET naming conventions
var list = query.Select(a => new B { X = a.A, Y = b.B, Z = c.C })
.ToList();
The compiler and runtime wouldn't care if your types had the same properties (not that they do in this case - they have different names) - they're still entirely separate types.
See more on this question at Stackoverflow