user3167619
user3167619

Reputation: 11

Confusion with Enumerable.Select in C#

I am new to the C# and .NET world. I am trying to understand the following statement.

var xyz = Enumerable.Repeat(obj, 1).ToList();
var abc = 
    xyz.Select(xyzobj => new res {
        foo = bar,
        xyzs = new [] {xyzobj},
    }).ToList();

I understand that Select takes in an object and a transformer function and returns a new form of the object. But here, it takes in a lambda expression with an enum value and another object.

I am little confused. Is the statement above similar to

var abc = xyz.Select(xyzobj => {
    //some work with xyzobj
    //and return object.
    }).ToList();

Can somebody explain the above statement actually does, my head just spins around with these statements all around in my new work location.

Can somebody direct me to good resources to understand lambda expressions and Enumeration.

Upvotes: 1

Views: 158

Answers (2)

Harrison
Harrison

Reputation: 3953

// Creates a IEnumerable<T> of the type of obj with 1 element and converts it to a List
var xyz = Enumerable.Repeat(obj, 1).ToList();


// Select takes each element in the List xyz 
// and passes it to the lambda as the parameter xyzobj.
// Each element is used to create a new res object with object initialization.
// The res object has two properties, foo and xyzs.  foo is given the value bar 
// (which was defined elsewhere).
// The xyzs property is created using the element from xyz passed into the lambda
var abc =  xyz.Select(
   xyzobj => new res {
        foo = bar,
        xyzs = new [] {xyzobj},
    }).ToList();

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149010

There are two main types of lambda expressions in C#.

Expression lambdas like this:

x => foo(x);

This takes a parameter x, and performs some transformation on it, foo, returning the result of foo(x) (though technically it may not return a value of the result type of foo(x) is void).

Statement lambdas look like this:

x => {
    // code block
}

This takes a parameter, x and performs some action on it, (optionally returning a value if an explicit return is provided). The code block may be composed of multiple statements, meaning you can declare variables, execute loops, etc. This is not supported in the simpler expression lambda syntax. But it's just another type of lambda.

If it helps you can think of the following as being equivalent (although they are not perfectly equivalent if you are trying to parse this as an Expression):

x => foo(x);

x => { return foo(x); }

Further Reading

Upvotes: 4

Related Questions