Home > Software engineering >  How to add items to a list from List<IEnumerable> using C# Linq
How to add items to a list from List<IEnumerable> using C# Linq

Time:12-19

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

CodePudding user response:

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 i.e. List<Reason> so use SelectMany()

  • Related