开发者

Convert IEnumerable<T> to string[]

开发者 https://www.devze.com 2023-04-08 10:17 出处:网络
i have an entity called Product class Product { public Id { get; set; } public Name { get; set; } } and i have a list of all products:

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 p开发者_StackOverflow社区roduct 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.


string[] s = products.Select(p => p.Name).ToArray();

Or, if you need Id + Name:

string[] s = products.Select(p => p.Id + ' ' + p.Name).ToArray();


use

string[] s = (from p in products select p.Id.ToString() + " " + p.Name.ToString()).ToArray();


This worked for me:

String.Join(";", mi_customer.Select(a => a.Id).Cast<string>().ToArray());

Where mi_customer must be your object, in my case is a table.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号