如何使用C#在一个foreach循环中使用两个数组

时间:2015-06-25 15:15:34

标签: c# php arrays multidimensional-array

如何使用foreach循环遍历两个arays? 我之前发现了这个,但这不适用于PHP而不是c#

$images = array('image1', 'image2', ...);
$descriptions = array('description1', 'description2', ...);

foreach (array_combine($images, $descriptions) as $image => $desc) {
  echo $image, $desc;
}

我的想法是有类似下面的内容

string[] ValueA = {1,2,3}
string[] ValueB = (a,b,c}

foreach(something here from ValueA && ValueB)
{
   methodNameHere(ValueA, ValueB); //method I am calling requires the two values
}

3 个答案:

答案 0 :(得分:2)

您将成为.Net 4中的Zip操作功能。 link1link2上的内容就是说明。

你会是这样的:

var alpha = new [] { A, B, C, D };
var day = new [] { "s", "s", "m", "t" };

var  alphasAndDays =  alpha.Zip(day, (n, w) => new { Alpha = n, Day = w });
foreach(var ad in  alphasAndDays)
{
   Console.WriteLine(aw.Alpha + aw.Day);
}

答案 1 :(得分:0)

一个简单的重复可以做到这一点:

 class Program
{
    static void Main(string[] args)
    {
        string[] setA = new string[3] {"1", "2", "3"};
        string[] setB = new string[3] { "a", "b", "c" };

        foreach (string val1 in setA) {

            foreach (string val2 in setB) {

                Program test = new Program();
                String printer = test.concatString(val1, val2);

                Console.WriteLine(printer);

            }
        }

        Console.ReadLine();

    }

    public string concatString(string value1, string value2) {

         String value3 = value1 + value2;
         return value3;
    }
}

答案 2 :(得分:0)

 int[] numbers = { 1, 2, 3, 4 };
            string[] words = { "one", "two", "three" };

            var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

            foreach (var item in numbersAndWords)
                Console.WriteLine(item);

            // This code produces the following output: 

            // 1 one 
            // 2 two 
            // 3 three