C # AddRange List <List <T>>

I need to populate a list from a list of List 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 pop up all the elements in one list, for example

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

But I get an error for the above AddRange, pls help someone write AddRange for this case

+4
source share
1 answer

Use SelectMany () to smooth the sequence of sequences:

var values = lstData.SelectMany(i => i.Items).ToList()
+8
source

Source: https://habr.com/ru/post/1538162/


All Articles