简体   繁体   中英

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. 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.

I am very new to LINQ, please guide. 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()

 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM