Mark
Mark

Reputation: 63

Using more than one object to iterate though in foreach loops

I have a multidimensional list:

    List<string>[] list = new List<string>[2];
    list[0] = new List<string>();
    list[1] = new List<string>();

And I iterate though the list as follows - but this only iterates through one list:

foreach (String str in dbConnectObject.Select()[0])
{
   Console.WriteLine(str);
}

Although I want to be able to do something like:

foreach (String str in dbConnectObject.Select()[0] & String str2 in dbConnectObject.Select()[1])
{
   Console.WriteLine(str + str2);
}

Upvotes: 4

Views: 257

Answers (4)

Adam
Adam

Reputation: 26937

You can try the following code. It also works if the sizes differ.

for (int i = 0; i < list[0].Count; i++)
{
    var str0 = list[0][i];
    Console.WriteLine(str0);
    if (list[1].Count > i)
    {
        var str1 = list[1][i];
        Console.WriteLine(str1);
    }
}

Upvotes: 0

FanAs
FanAs

Reputation: 199

Use LINQ instead:

foreach (var s in list.SelectMany(l => l)) { Console.WriteLine(s); }

Upvotes: -1

Steve B
Steve B

Reputation: 37710

If you want to sequentially iterate through the two lists, you can use IEnumerable<T>.Union(IEnumerable<T>) extension method :

IEnumerable<string> union = list[0].Union(list[1]);

foreach(string str int union)
{
     DoSomething(str);
}

If you want a matrix of combination, you can join the lists :

var joined = from str1 in list[0]
             from str2 in list[1]
             select new { str1, str2};


foreach(var combination in joined)
{
    //DoSomethingWith(combination.str1, combination.str2);
    Console.WriteLine(str + str2);
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

If the lists are of the same size, you can use Enumerable.Zip:

foreach (var p in dbConnectObject.Select()[0].Zip(dbConnectObject.Select()[1], (a,b) => new {First = a, Second = b})) {
    Console.Writeline("{0} {1}", p.First, p.Second);
}

Upvotes: 6

Related Questions