I was looking for a solution to convert each object's properties on a List to some arrays when finally I found this
Then I found this code
MyList.Select(x=>x.Name).ToArray();
which is the solution to my problem. But I still don't understand on what the variable 'x' means. can anyone could explain to me briefly on how this syntax work?
The LINQ
.Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
extension method expects a Func which takes one argument and returns an object/value of another (or even the same) type.You have several ways to specify which function to execute for each item in your enumerable:
x => x.Name
:x
is the input parameter,x.Name
is the result. Could also be written as lambda statement:x => { return x.Name; }
. Lambda expressions are a very concise way to write short methods which might only be used once. (In addition, they collect their surrounding scope in closures – but this is irrelevant in the context of your question)delegate(YourType x) { return x.Name; }
Method group: Define a named method somewhere else, and specify its name:
.Select(this.SelectName)
.SelectName
would be written as:LINQ extension methods generally work on instances of
IEnumerable<T>
, so any type (mostly collections) which can be iterated/enumerated..Select()
is used to transform one enumerable of typeIEnumerable<TSource>
to another enumerable of typeIEnumerable<TResult>
. Note, that theselector
function passed as parameter to.Select()
is only executed, once the enumerable gets enumerated (by means offoreach
,.ToList()
,.ToArray()
, or others).With LINQ you focus more on a data centric view of your types. You don't care if
.Select()
internally uses foreach, for, or any other way to get to your collection's items. It might even parallelize the operation (.AsParallel
).Of course, most LINQ invocations can be rewritten with simple code, for example: