使用foreach循环遍历列表

时间:2013-04-16 18:55:27

标签: c# list foreach

当尝试循环列表如下所示时,我将如何实现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 }
   }
};

6 个答案:

答案 0 :(得分:4)

foreach(var product in myCollection.Products)
{
    // Do something with product
}

答案 1 :(得分:3)

foreach (var item in myCollection.Products) 
{
   //your code here
}

答案 2 :(得分:2)

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

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

foreach(var product in myCollection.SelectMany(col => col.Products))
    ; // work on product

答案 3 :(得分: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...
 }

答案 4 :(得分:1)

尝试:

 foreach(Product product in myCollection.Products)
 {

 }

答案 5 :(得分:0)

试试这个.-

foreach (var product in myCollection.Products) {
    // Do your stuff
}