如何使用foreach
循环遍历两个aray?我以前发现过这个,但那是为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
}
您将是.Net 4功能中的Zip操作。链接1和链接2上的这是说明。
你会对的,比如:
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);
}
一个简单的重复就可以做到这一点:
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;
}
}
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