[英]How to add items to a list from List<IEnumerable> using C# Linq
I have a List T, and I have a List of IEnumerable query.我有一个列表 T,还有一个 IEnumerable 查询列表。 I want to add the selection/ all the values of List of IEnumerable to this List T. I tried below but it shows error: Cannot implicitly convert type 'List IEnumerable ' to a generic list Reason.我想将 IEnumerable 列表的选择/所有值添加到此列表 T。我在下面尝试但它显示错误:无法将类型“List IEnumerable”隐式转换为通用列表原因。
I am very new to LINQ, please guide.我对 LINQ 很陌生,请指导。 I tried the following:我尝试了以下内容:
public class Reason
{
public int ReasonId { get; set; }
public int OrderId { get; set; }
}
var newReason = new List<Reason>();
newReason = reasons?.Select(res => res.Select(re => new Reason()
{
ReasonId = re.ReasonId,
OrderId = re.OrderId,
})).ToList();
You are trying to create list of Reason
instance by flattening nested reasons
list, try SelectMany()
您正在尝试通过展平嵌套reasons
列表来创建Reason
实例列表,请尝试SelectMany()
newReason = reasons?.SelectMany(re => new Reason()
{
ReasonId = re.ReasonId,
OrderId = re.OrderId,
})?.ToList()
?? new List<Reason>();
Select()
inside Select()
will return IEnumerable<IEnumerable<Reason>>
, and you need flatten list of Reason
class ie List<Reason>
so use SelectMany()
Select()
里面的Select()
将返回IEnumerable<IEnumerable<Reason>>
,你需要展平Reason
类的列表,即List<Reason>
所以使用SelectMany()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.