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 を使用して反復処理を行うことができますが、製品だけが必要な場合は、あまりきれいではありません。

SelectMany代わりに、LINQ拡張メソッドを使用してコレクションをフラット化できます。

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 に答える