4

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);
}

4 Answers 4

6

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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);
}

1 Comment

Union will exclude duplicates from the return set. I don't think that this is desired. I would prefer Concat although Zip might be more suitable.
0

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);
    }
}

1 Comment

Why are you using the Enumerable extension methods on pure Lists? (Count() instead of Count, ElementAt instead of the indexer)
-1

Use LINQ instead:

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

1 Comment

Ths does not join both lists with each other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.