Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Elegant" way to get list of list of property values from List<T> of objects?

Tags:

c#

.net

generics

Say I have a Customer class with the usual properties: CustomerID, Name, etc.

As a result of a query, I get a generic list of Customer objects: List<Customer>

Is there an elegant way to get an array/list of CustomerID or Name property values from this generic list? (i.e. string[] customerIDs = ???? )

I know I could do a foreach and fill an array during the loop, but was just wondering if there were a more elegant way through LINQ extensions and/or lambda expressions to do this.

Thanks.

like image 352
WayneC Avatar asked Feb 27 '23 21:02

WayneC


1 Answers

If you're using LINQ, you can do the following:

string[] customerIDs = list.Select(x => x.ID).ToArray();
like image 57
FryGuy Avatar answered May 11 '23 04:05

FryGuy