用foreach循环遍历list

本文关键字:list 遍历 循环 foreach | 更新日期: 2023-09-27 18:09:35

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

用foreach循环遍历list

foreach(var product in myCollection.Products)
{
    // Do something with product
}
foreach (var item in myCollection.Products) 
{
   //your code here
}

如果你想让我们帮助你,你必须向我们展示所有相关的代码。

无论如何,如果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...
 }

看起来您有一个包含集合的集合。在这种情况下,您可以使用嵌套foreach来迭代,但如果您只想要产品,则不太美观。

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

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

Try with:

 foreach(Product product in myCollection.Products)
 {
 }

试试这个。-

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