Can someone please explain to me the following method? I don’t quite understand what it does, and how it does it.
private List<Label> CreateLabels(params string[] names)
{
return new List<Label>(names.Select(x => new Label { ID = 0, Name = x }));
}
Let’s separate it into different bits:
This means we’re declaring a method returning a list of
Labelreferences. We’re taking an array of string references as a parameters, and it’s declared as a parameter array which means callers can just specify the arguments like this:(Or they can explicitly pass in an array of strings as normal.)
Now to understand the body, we’ll split it up like this:
The second and third lines should be fairly simple – it’s just constructing a
List<Label>from a sequence of labels, and then returning it. The first line is likely to be the one causing problems.Selectis an extension method on the genericIEnumerable<T>type (a sequence of elements of typeT) which lazily returns a new sequence by executing a projection in the form of a delegate.In this case, the delegate is specified with a lambda expression like this:
That says, “Given
x, create aLabeland set its ID property to 0, and itsNameproperty tox.” Here the type ofxis inferred to bestringbecause we’re callingSelecton a string array. This isn’t just using a lambda expression, but also an object initializer expression. Thenew Label { ID = 0, Name = x }part is equivalent to:We could have written a separate method to do this:
and then called:
That’s effectively what the compiler’s doing for you behind the scenes.
So the projection creates a sequence of labels with the names given by the parameter. The code then creates a list of labels from that sequence, and returns it.
Note that it would (IMO) be more idiomatic LINQ to have written:
rather than explicitly creating the
List<Label>.