Reputation: 67
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 }
}
};
Upvotes: 0
Views: 457
Reputation: 13551
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...
}
Upvotes: 2
Reputation: 16536
Try this.-
foreach (var product in myCollection.Products) {
// Do your stuff
}
Upvotes: 0
Reputation: 164341
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
Upvotes: 2
Reputation: 245489
foreach(var product in myCollection.Products)
{
// Do something with product
}
Upvotes: 4
Reputation: 8715
foreach (var item in myCollection.Products)
{
//your code here
}
Upvotes: 3