mameesh mameesh - 1 year ago 65
C# Question

How to use inline method when assigning to object

With LINQ to objects is there a way to assign a property using an inline method without defining the method separately?

For example, I have a list I am iterating over (results) to create a new list (testObjects) with the assigned values from the LINQ statement. The TestProp property has complex logic to populate it, so I want to perform that logic within an inline method in the LINQ statement, rather than calling a separate method.

Lets say for simplicity sake when assigning TestProp below, I have a property on results called DriverID which is a string value. In this assignment I need to make sure that the DriverID is a GUID before assigning it, and if so, assign it to TestProp. If not assign new Guid();

var testObjects = results.Select(row => new
Name = row.Name,
Address = row.Address,
TestProp = //I don't want to call a method like ConvertToGUID() here, I would rather do the work directly in the LINQ statement with something like
//Do the work here instead by performing all the logic inline within this LINQ statement.

I know you can call a method here directly to assign TestProp, but is there a way to keep all the method logic right in the 1 LINQ call property assignment instead so I do not have to define a separate method for the work that needs to occur to get the TestProp value?

Answer Source

If you're using LINQ to Objects, your lambda expression only needs to be convertible to a delegate. So you can use something like:

var testObject = results.Select(row => {
    // Several statements here, as you wish
    int x = row.X;
    int y = row.Y;
    int z = x + y;
    return new {
        testProp = z,

This won't help with LINQ providers using Queryable though, as statement-bodied lambdas are not convertible to expression trees.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download