Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# AddRange List<List<T>>

Tags:

c#

list

linq

I need to populate List from List of List objects or List of Enumarable Objects.

Consider the class

 public class Data
    {
       public int ID;
       public List<string> Items;
    }

 List<Data> lstData= new List<Data>();
 lstData.Add(new Data { ID = 1, Items = new List<string> { "item1", "item2" } });
 lstData.Add(new Data { ID = 2, Items = new List<string> { "item3", "item4" } });

Now , I want to popuplate all the items into one list, like

List<string> values = new List<string>();
values.AddRange(lstData.Select(a => a.Items));

But I am getting error for above AddRange, pls help anyone to write AddRange for this case

like image 870
kombsh Avatar asked Feb 14 '23 03:02

kombsh


1 Answers

Use SelectMany() to flatten a sequence of sequences:

var values = lstData.SelectMany(i => i.Items).ToList()
like image 86
sloth Avatar answered Feb 15 '23 15:02

sloth