i have an entity called Product
class Product
{
public Id { get; set; }
public Name { get; set; }
}
and i have a list of all products:
IEnumerable<Product> products = _productRepository.GetAll()
i want to get an array of strings from this list of products this array will contains the product Id + Product Name, so when i try to cast it using the following code:
string[] s = products.Cast<string>().ToArray();
i got the following exception:
Unable to cast object of type 'Product' to type 'System.String'
the exception really makes alot fo scence, so if i had a method
string ProductToString(Product p)
{
return p.Name;
}
or an override to ToString() for the product object so how i can use this method to get the list of string[] from IEnumerable ?
Well, given that method you can use1:
string[] s = products.Select<string>(ProductToString).ToArray();
However, it would be more idiomatic to do this without a separate method, usually, using a lambda expression:
// Matches ProductToString, but not your description
string[] s = products.Select(p => p.Name).ToArray();
I'd only use a separate method if it was going to be called from various places (ensuring consistency) or did a lot of work.
EDIT: I've just noticed that your description (wanting ID + name) doesn't actually match the ProductToString
method you've given (which just gives the name). For the ID + name I'd use:
string[] s = products.Select(p => p.ID + " " + p.Name).ToArray();
or
string[] s = products.Select(p => string.Format("{0} {1}", p.ID, p.Name))
.ToArray();
Or you could just change your ProductToString
method, of course.
Alternatively, you could override ToString()
in Product
, if this is usually how you want to convert a Product
to a string
. You could then either use a method group conversion or a lambda expression to call ToString
.
1 It's possible that you don't need to specify the type argument explicitly - that:
string[] s = products.Select(ProductToString).ToArray();
will work fine - the rules for type inference and method group conversions always confuse me and the compiler behaviour has changed slightly over time. A quick test just now looks like it does work, but there could be subtleties in slightly different situations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With