How to typecast the first object from an IEnumerable?

C

craigkenisston

I'm working on someone else code I don't quite understand it.

It has a class with a method like :
private IEnumerable<Product> GetProducts(int count)
{
blah, blah
}

And I need to get an instance of the first object of that list:

Product prod = GetProducts(1);

I get a compile time error:
**************
"Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<Products>' to 'Products'. An
explicit conversion exists (are you missing a
cast?) C:\Websites\BlogSK\Admin\Login.aspx.cs 24 18 C:\Websites\BlogSK\"
**************
I tried to:
Product prod = (Product)GetProducts(1);

And got it to compile, but then I get a runtime error:
"Unable to cast object of type
'System.Collections.Generic.List`1[Products]' to type 'Products'."

Any kind of help is appreciated.
 
M

Marc Gravell

If the result was IList<Product>, you could use

Product prod = GetProducts(1)[0];

Since the result is IEnumerable / IEnumerable<Product> (and doesn't
provide an indexer), you have to enumerate it...

Product prod = null;
foreach(Product p in GetProducts(1)) {
prod = p;
break; // short-circuit in case multiple returned items
}

If you are going to be doing a lot more with the enumerable set (which
I doubt, as it probably only 1 item), the following can be a handy way
to make more functionality available:

List<Product> products = new List<Product>(GetProducts(count));
Product firstProduct = products[0];
// lost of other things involving "products"...

Any use?

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top