Divide it into different bits:
private List<Label> CreateLabels(params string[] names)
This means that we are declaring a method that returns a list of Label references. We take an array of string references as parameters and declare it as an array of parameters, which means that callers can simply specify the following arguments:
List<Label> labels = CreateLabels("first", "second", "third");
(Or they can explicitly pass in an array of strings as usual.)
Now, to understand the body, we will separate it as follows:
IEnumerable<Labael> labels = names.Select(x => new Label { ID = 0, Name = x }); List<Label> list = new List<Label>(labels); return list;
The second and third lines should be fairly simple - they simply construct a List<Label> from a sequence of labels, and then return it. The first line is likely to cause problems.
Select is an extension method for the generic type IEnumerable<T> (a sequence of elements of type T ), which lazily returns a new sequence by performing a projection as a delegate.
In this case, the delegate is set using the lambda expression as follows:
x => new Label { ID = 0, Name = x }
This says: "Given x , create a Label and set its ID property to 0, and its Name property to x ." Here, the type x defined as string , because we call Select in an array of strings. This is not just using a lambda expression, but also an object initializer expression. The new Label { ID = 0, Name = x } equivalent:
Label tmp = new Label(); tmp.ID = 0; tmp.Name = x; Label result = tmp;
We could write a separate method for this:
private static Label CreateLabel(string x) { Label tmp = new Label(); tmp.ID = 0; tmp.Name = x; return tmp; }
and then called:
IEnumerable<Label> labels = names.Select(CreateLabel);
What the compiler does for you behind the scenes is effective.
Thus, the projection creates a sequence of labels with the names specified by the parameter. The code then creates a list of tags from this sequence and returns it.
Note that it (IMO) will be more idiomatic LINQ to write:
return names.Select(x => new Label { ID = 0, Name = x }).ToList();
instead of explicitly creating a List<Label> .