A simple linq question: using linq to get an array of properties

Suppose we have a simple class

public class Foo { public string FooName; } 

Now we want to do simple work on it.

 public void SomeCallerMethod(List<Foo> listOfFoos) { string[] fooNames = listOfFoo. // What to do here? } 

If I even knew which method to call, I could probably find the rest of the peices.

+7
c # linq-to-objects
source share
1 answer

You want to convert the list of your class to an array of strings. The ideal method for this is Select , which works with each element in an enumerable and creates a new enumerable based on the type you are returning.

You need to put the lambda expression in the select method, which returns a name that will simply be β€œfor each element, select a name”.

Then you need to pass the result as an array.

 string[] fooNames = listOfFoos.Select(foo => foo.FooName).ToArray(); 

Or using another syntax:

 string[] fooNames = (from foo in listOfFoos select foo.FooName).ToArray(); 
+16
source share

All Articles