我有:
public class MyObject
{
public int Id { get; set; }
public List<RandomObject> Items { get; set; }
}
和
public class NewObject
{
public int Id { get; set; }
public RandomObject Item { get; set; }
}
如何使用LINQ按字段List<MyObject>
将List<NewObject>
的实例转换为Items
?
答案 0 :(得分:3)
假设您有myObject
类型的变量MyObject
。在这种情况下
List<NewObject> newObjects = myObject.Items.Select(i => new NewObject
{
Item = i,
Id = myObject.Id
}).ToList();
如果您的变量myObjects
包含List<MyObject>
类型的列表,那么您只需要添加SelectMany
:
List<NewObject> = myObjects.SelectMany(o => o.Items.Select(i => new NewObject
{
Item = i,
Id = myObject.Id
})).ToList();