Freigeben über


Iterating over a nested Member

You have a Collection of Products. Every product effectively maps to an Item. Now I needed to bind this Product collection to a grid and display the item name. So basically it would be something like prod[i].Item.Name or any other property can be accessed for item. Basically the idea is to Iterate over an inner member inside every element of the parent collection.

If you wanted to bind this with a GridView you can have very complex Databinding syntax for this by casting the items etc. Another option that I wanted to bring up here is creating an IEnumerable view using the parent collection.

public class ProdItemList:IEnumerable

{

    private List<Product> Products;

   

    public ProdItemList(List<Product> products)

    { this. Products = products; }

    public IEnumerator GetEnumerator()

    {

        foreach (Product product in Products)

            yield return product.Item;

    }

}

You can then bind the DataSource and it would effectively bind to the properties in Item. With something like ItemGrid.DataSource = new ProdItemList(products);

 I really liked this article regarding IEnuerable and 2.0. I am sure there are many approaches for this but just thought i'd put it down here for further discussion.