0

当尝试遍历如下列表时,我将如何实现foreach循环?

ProductCollection myCollection = new ProductCollection
{
   Products = new List<Product>
   {
      new Product { Name = "Kayak", Price = 275M},
      new Product { Name = "Lifejacket", Price = 48.95M },
      new Product { Name = "Soccer ball", Price = 19.60M },
      new Product { Name = "Corner flag", Price = 34.95M }
   }
};
4

6 回答 6

4
foreach(var product in myCollection.Products)
{
    // Do something with product
}
于 2013-04-16T18:57:35.203 回答
3
foreach (var item in myCollection.Products) 
{
   //your code here
}
于 2013-04-16T18:57:27.310 回答
2

似乎您有一个包含集合的集合。在这种情况下,您可以使用嵌套的 foreach 进行迭代,但如果您只想要产品,它就不太漂亮了。

相反,您可以使用 LINQSelectMany扩展方法来展平集合:

foreach(var product in myCollection.SelectMany(col => col.Products))
    ; // work on product
于 2013-04-16T18:58:03.160 回答
2

如果您希望我们帮助您,您必须向我们展示所有相关代码。

无论如何,如果 ProductCollection 是这样的:

 public class ProductCollection 
 {
      public List<Product> Products {get; set;}
 }

然后像这样填写:

 ProductCollection myCollection = new ProductCollection
    {
        Products = new List<Product>
        {
            new Product { Name = "Kayak", Price = 275M},
            new Product { Name = "Lifejacket", Price = 48.95M },
            new Product { Name = "Soccer ball", Price = 19.60M },
            new Product { Name = "Corner flag", Price = 34.95M }
        }
    };

并像这样迭代:

 foreach (var product in myCollection.Products) 
 {
      var name = product.Name;
      // etc...
 }
于 2013-04-16T19:02:28.453 回答
1

尝试:

 foreach(Product product in myCollection.Products)
 {

 }
于 2013-04-16T19:03:30.183 回答
0

尝试这个。-

foreach (var product in myCollection.Products) {
    // Do your stuff
}
于 2013-04-16T18:58:57.307 回答