[英]IQueryable<a> to list<b> type conversion, when a & b having similar signature using LINQ
I'm having some basic problem with linq, I tried to google but didn't get the desired reuslt. 我有一些基本问题与linq,我试图谷歌但没有得到理想的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. 这里A是数据上下文类,它是在创建.edmx文件时由框架生成的,B是我的自定义类,用于将数据传递给UI。 I'm querying the data base using A & getting a iqueryable list. 我正在使用A查询数据库并获取可查询的列表。 Now I need to convert this list into another list of type B. How can I do that? 现在我需要将此列表转换为另一个类型B的列表。我该怎么做?
You need to use Select
to project from one type to another, then ToList
to create a list: 您需要使用Select
从一种类型投射到另一种类型,然后使用ToList
创建一个列表:
// 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. 编译器和运行时不关心你的类型是否具有相同的属性(在这种情况下它们不具有相同的属性 - 它们具有不同的名称) - 它们仍然是完全独立的类型。
Assume your query method returns an IEnumerable<A>
you can do the following. 假设您的查询方法返回IEnumerable<A>
您可以执行以下操作。
IEnumerable<A> myList = SomeMethod();
var myModelList = myList.Select(a => new B(){x = a.A, y = a.B, z = a.C});
You will use projections when selecting. 选择时将使用投影。
var myQuery = (from a in context.A
select new B{
x = a.A,
y = a.B,
z = a.C
});
return myQuery.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.