Kevin M
Kevin M

Reputation: 5496

C# AddRange List<List<T>>

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

Upvotes: 4

Views: 274

Answers (1)

sloth
sloth

Reputation: 101042

Use SelectMany() to flatten a sequence of sequences:

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

Upvotes: 8

Related Questions