Rogerto
Rogerto

Reputation: 317

How to loop through a List of Lists and add each element to a new List

How do I loop through every element in a List of Lists and then add these elements to a new List as per the details below:

I have a List of Lists containing Strings as such:

List< List<String> > myStringList;

How do I loop through each element and then add each individual element to a new List as such:

List<String> myNewStringList;

Upvotes: 1

Views: 2700

Answers (3)

PRATHIV
PRATHIV

Reputation: 570

you can also use .forEach method on the myStringList .

Upvotes: 0

talevineto
talevineto

Reputation: 51

Took this code from an old project, hope it solves it for you, same as the one from TheAlphamerc but prettier.

List<String> _plainList(List<List<String>> inputList){
    List<String> _plainList = [];

    for (List<String> l in inputList)
        for (String s in l)
            _plainList.add(s);

    return _plainList;
}

Upvotes: 0

TheAlphamerc
TheAlphamerc

Reputation: 916

The result can be achieved by iterating myNewStringList and its inner list.

 
 List<List<String> > myStringList;

 List<String> myNewStringList = [];
 
 /// Assuming myStringList has some data in it.
 for(var list in myNewStringList){
   for(var item in list){
      myNewStringList.add(item);
   }  
 }

Upvotes: 3

Related Questions