Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple linq question: using linq to get an array of properties

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.

like image 372
Joel Barsotti Avatar asked May 17 '10 07:05

Joel Barsotti


People also ask

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

How use any LINQ query?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

What are LINQ queries in C#?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


1 Answers

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();
like image 193
cjk Avatar answered Oct 14 '22 14:10

cjk