使用foreach循环遍历两个数组

时间:2014-10-09 11:07:42

标签: c# arrays

每当我按下“全部显示”按钮时,我想要显示所有“Artikelen”(文章)和“PrijsArtikel”(文章价格)。

显示三篇随机文章及其相关价格的代码,但现在我想让它在另一种方法中显示所有数组。

我必须使用foreach()

string[] Artikelen = {"schoen", "muts", "sjaal", "rok", "jurk", "Gouden Horloge",
        "Gouden Ketting", "Handschoenen", "Sokken", "Beenwarmers" };
double[] PrijsArtikel = { 89.80, 17.99, 10.00, 45.00, 780.00, 7800.00, 1000, 15.00, 2.00, 10.00 };

private void btnRandom_Click(object sender, RoutedEventArgs e)
{   
    txtOplossing.Text = "";

    string temp;
    temp = string.Empty;

    Random rnd = new Random();
    int WillekeurigGetal = 0;

    for (int i = 0; i < 3; i++)
    {
        WillekeurigGetal = rnd.Next(0, 10);
        temp = (Artikelen[WillekeurigGetal]) + 
        ("  \t = \t ") +     (PrijsArtikel[WillekeurigGetal]) + (" Euro \n");
        txtOplossing.Text += temp.ToString();
    }
}

private void btn_All_Items_Click(object sender, RoutedEventArgs e)
{

}

2 个答案:

答案 0 :(得分:1)

您也可以创建适当的数据结构

public class  ArticleForSale
{
    public string Name{get; set;}
    public decimal Price{get;set;}

    public override string ToString()
    {
        return Name +"\t=\t" + Price;
    }
}
List<ArticleForSale> articleForSale = new List<ArticleForSale>{
    new ArticleForSale{ Name= "schoen", Price=89.80m },
    new ArticleForSale{ Name= "muts", Price= 17.99m},
    new ArticleForSale{ Name= "sjaal", Price=89.80m },
    new ArticleForSale{ Name= "rok", Price= 10.00m },
    new ArticleForSale{ Name= "jurk", Price=45.00m },
    new ArticleForSale{ Name= "Gouden Horloge", Price=780.00m },
    new ArticleForSale{ Name= "Gouden Ketting", Price=7800.00m},
    new ArticleForSale{ Name=  "Handschoenen", Price=1000m},
    new ArticleForSale{ Name= "Sokken", Price=89.80m },
    new ArticleForSale{ Name= "Beenwarmers", Price=89.80m },
};

foreach(var art in articleForSale)
{
    Console.WriteLine(art);
}

for(int i = 0; i < articleForSale.Count(); i++)
{
    Console.WriteLine(articleForSale[i]);
}

你拥有的东西也可以从两个阵列创建你的列表

string[] Artikelen = {"schoen", "muts", "sjaal", "rok", "jurk", "Gouden Horloge",
    "Gouden Ketting", "Handschoenen", "Sokken", "Beenwarmers" };
decimal[] PrijsArtikel = { 89.80m, 17.99m, 10.00m, 45.00m, 780.00m, 7800.00m, 1000m, 15.00m, 2.00m, 10.00m };

var articleForSale = Artikelen.Zip(PrijsArtikel, 
                                    (article, price)=> 
                                    { 
                                        return new ArticleForSale { Name= article, Price=price };
                                    }).ToList();

您可以选择使用for循环或foreach迭代。

答案 1 :(得分:0)

以下是使用foreach,将包括artikelen和prijsArtikel

中的所有内容
var outputStr = "";
foreach (var article in artikelen)
    outputStr += article + ", ";

foreach (var price in prijsArtikel)
   outputStr += price + ", ";

但我认为你需要的是以下内容:

var outputStr = "";
for (int i = 0; i < Math.Min(artikelen.Length, prijsArtikel.Length); i++)
    outputStr += artikelen[i] + " " + prijsArtikel[i] + "\n";