从 Linq 中的另一个列表项创建列表
Creating lists from another list's item in Linq
我有一个自定义汽车对象列表 List<Car>
。汽车 class 有两个属性 'BrandName' 和 'Models',定义如下。
public class Car
{
public string BrandName {get; set;}
public List<string> Models {get; set;}
}
“List”对象的数据是从 API 填充的,如下所示。它 returns 接近 200 行。出于说明目的,已使用以下两项实例化该对象。该对象是从具有此结构的 API 返回的,我无法控制数据的结构和发送方式。
List<Car> listCarObj = new List<Car>(){
new Car(){ BrandName = "Mercedes", Models = new List<string>(){"Class A", "Class E"}},
new Car(){ BrandName = "BMW", Models = new List<string>(){"X Series", "E Series"}}
}
如何使用 Linq 将此列表转换为 IEnumerable 或其他具有以下格式数据的匿名类型列表?
var obj = new[] {new {brand = "Mercedes", model = "Class A"},
new {brand = "Mercedes", model = "Class E"},
new {brand = "BMW", model = "X Series"},
new {brand = "BMW", model = "E Series"}};
提前致谢..
你为什么不进行 linq 查询,在其中你 select 来自 listCarObj
的每个对象,并且对于列表中的每个元素,获取所有模型和 return 匿名类型?
类似于:
var obj = from p in listCarObj
from q in p.Models
select new {
brand=p.BrandName,
model = q
};
您可以使用 SelectMany 来展平您的 Models
,然后像这样投影它:-
var result = listCarObj.SelectMany(x => x.Models,
(carObj, model) => new {
carObj.BrandName, model
});
这是一种使用 SelectMany
和嵌套 Select
的方法
var result = listCarObj.SelectMany(x => x.Models.Select(y => new { model = y,brand = x.BrandName }));
我有一个自定义汽车对象列表 List<Car>
。汽车 class 有两个属性 'BrandName' 和 'Models',定义如下。
public class Car
{
public string BrandName {get; set;}
public List<string> Models {get; set;}
}
“List”对象的数据是从 API 填充的,如下所示。它 returns 接近 200 行。出于说明目的,已使用以下两项实例化该对象。该对象是从具有此结构的 API 返回的,我无法控制数据的结构和发送方式。
List<Car> listCarObj = new List<Car>(){
new Car(){ BrandName = "Mercedes", Models = new List<string>(){"Class A", "Class E"}},
new Car(){ BrandName = "BMW", Models = new List<string>(){"X Series", "E Series"}}
}
如何使用 Linq 将此列表转换为 IEnumerable 或其他具有以下格式数据的匿名类型列表?
var obj = new[] {new {brand = "Mercedes", model = "Class A"},
new {brand = "Mercedes", model = "Class E"},
new {brand = "BMW", model = "X Series"},
new {brand = "BMW", model = "E Series"}};
提前致谢..
你为什么不进行 linq 查询,在其中你 select 来自 listCarObj
的每个对象,并且对于列表中的每个元素,获取所有模型和 return 匿名类型?
类似于:
var obj = from p in listCarObj
from q in p.Models
select new {
brand=p.BrandName,
model = q
};
您可以使用 SelectMany 来展平您的 Models
,然后像这样投影它:-
var result = listCarObj.SelectMany(x => x.Models,
(carObj, model) => new {
carObj.BrandName, model
});
这是一种使用 SelectMany
和嵌套 Select
var result = listCarObj.SelectMany(x => x.Models.Select(y => new { model = y,brand = x.BrandName }));