Guys tell me how in C # without a heap of cycles to loop through several List'ov? For example, there are 3 arrays.

List<string> list1 = new List<string>() {"1","2","3"}; List<string> list2 = new List<string>() {"4","5"}; List<string> list3 = new List<string>() {"6",};`` 

How to loop through them in one cycle?

    3 answers 3

    If simply, then:

     foreach (var item in list1.Concat(list2).Concat(list3)) { ... } 

    If you need to connect an arbitrary number of lists, you can write a universal function:

     public static IEnumerable<T> ConcatAll<T>( this IEnumerable<T> root, params IEnumerable<T>[] streams) { IEnumerable<T> result = root; foreach (var stream in streams) { result = result.Concat(stream); } return result; } 

    Using:

     foreach (var item in list1.ConcatAll(list2, list3)) { ... } 

      With Linq, this is done like this:

       foreach (var item in new [] { list1, list2, list3 }.SelectMany(list => list)) { // ... } 

        Can be done in two cycles, such as

         using System; using System.Collections.Generic; public class Test { public static void Main() { List<string> list1 = new List<string>() {"1","2","3"}; List<string> list2 = new List<string>() {"4","5"}; List<string> list3 = new List<string>() {"6",}; foreach ( List<string> list in new List<string>[] { list1, list2, list3 } ) { foreach ( string s in list ) Console.Write( s ); } } } 

        Console output

         123456