简体   繁体   中英

Iterating through list with foreach loop

When trying to loop through a list as below, how would I implement a foreach loop?

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)
{
    // Do something with product
}
foreach (var item in myCollection.Products) 
{
   //your code here
}

It seems you have a collection containing a collection. In this case you could use a nested foreach to iterate, but if you just want the products, it is not too pretty.

Instead, you could use the LINQ SelectMany extension method to flatten the collection:

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

You have to show us all relevant code if you want us to help you.

Anyway, if ProductCollection is like:

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

then fill it like:

 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 }
        }
    };

and iterate like:

 foreach (var product in myCollection.Products) 
 {
      var name = product.Name;
      // etc...
 }

Try with:

 foreach(Product product in myCollection.Products)
 {

 }

Try this.-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM