15

Lets say we have a simple class

public class Foo
{
    public string FooName;
}

Now we want to do some simple work on it.

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

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

0

1 Answer 1

26

You want to transform a list of your class into an array of strings. The ideal method for this is Select, which operates on each element on the enumerable and builds a new enumerable based on the type you return.

You need to put a lambda expression into the select method that returns the name, which will simply be "for each element, select the name".

You then need to cast the output as an array.

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

Or, using the other syntax:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.