Looping through 2 Lists at once

前端 未结 7 452

I have two lists that are of the same length, is it possible to loop through these two lists at once?

I am looking for the correct syntax to do the below



        
7条回答
  •  花落未央
    2021-01-31 11:01

    I recommend using plain old for loop, but you should consider different array lengths. So

    for(int i=0; i

    can turn into

    for(int i = 0; i < Math.Min(ListA.Length, ListB.Lenght); i++)
    {
        Console.WriteLine(ListA[i].ToString() + ", " + ListB[i].ToString());
    }
    

    or even into

        for(int i = 0; i < Math.Max(ListA.Length, ListB.Lenght); i++)
        {
            string valueA = i < ListA.Length ? listA[i].ToString() : "";
            string valueB = i < ListB.Length ? listB[i].ToString() : "";
    
            Console.WriteLine(valueA+ ", " + valueB);
        }
    

提交回复
热议问题