none
How to iterate list of list in C#? RRS feed

  • Question

  • Hi,

    I have list of list of strings.

    List<List<string>> mList = new List<List<string>>();
    
    List<string> listA = new List<string>();
    
    List<string> listB= new List<string>();
    
    List<string> listC = new List<string>();
    
    mList.Add(listA);
    
    mList.Add(listB);
    
    mList.Add(listC);


    How to iterate mList and print each value.


    • Edited by sgrm123 Wednesday, May 15, 2019 11:52 AM
    Wednesday, May 15, 2019 11:51 AM

Answers

All replies

  • foreach( var outer in mList )
    {  
      foreach( var inner in outer )
      {   
        Console.WriteLine( inner ); 
      }
    }

    Andy

    Wednesday, May 15, 2019 11:58 AM
  • foreach (string s in mList.SelectMany(k => k))
    {
        Console.WriteLine(s);
    }
    


    Wednesday, May 15, 2019 1:33 PM
  • foreach (string s in mList.SelectMany(k => k))
    {
        Console.WriteLine(s);
    }


    If there were ever a shortage of space to write code, then this is perfect.

    However, I feel sorry for anyone who's not a LINQ geek.


    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

    Wednesday, May 15, 2019 1:41 PM
  • Retrieve List elements

    You can retrieve items from list collection by using for loops.

    I hope this will help...

    Add string values in the List:

    List<string> colors = new List<string>();

    colors.Add("Red");

    colors.Add("Blue");

    colors.Add("Green");

    foreach loop:

    foreach (string color in colors)

    {

        MessageBox.Show(color);

    }

    for loop:

    for (int i = 0; i < colors.Count; i++)

    {

        MessageBox.Show(colors[i]);

    }

    Wednesday, May 15, 2019 1:53 PM