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:
- Lambda expressions: what you posted in your question.
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)
- Anonymous delegate: Mostly the same as above. Would be written as
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:
private string SelectName(YourType x) {
return x.Name;
}
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 type IEnumerable<TSource>
to another enumerable of type IEnumerable<TResult>
. Note, that the selector
function passed as parameter to .Select()
is only executed, once the enumerable gets enumerated (by means of foreach
, .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:
var nameList = List<String>(MyList.Count);
foreach(var item in MyList) {
nameList.Add(item.Name);
}
var array = nameList.ToArray(); // this is still LINQ,
// but I didn't want to bother
// with re-allocating the array
// or with using indexing