Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq select self reference during creation in C#

Tags:

c#

linq

Basically what I want is the same that is answered here but in C#: Self-references in object literal declarations

What I have is this code:

private List<myObject> myFunction()
{
    return myList.Select(l => new myObject
    {
        propA = 6,
        propB = 3,
        propC = propA + propB
    }
    ).ToList();
}

Of course it does not work, because I cannot reference propA and propB this way. What it the right way to do it?

Thank you

like image 890
Carlos Avatar asked Oct 26 '25 14:10

Carlos


1 Answers

You can use body in lambda expression:

private List<myObject> myFunction()
{
    return myList.Select(l => 
    {
        var myObject = new myObject
        {
            propA = 6,
            propB = 3        
        };

        myObject.propC = myObject.propA + myObject.propB;

        return myObject;

    }).ToList();
}

Or you can return sum in getter of propC:

public int propC 
{
    get
    {
        return propA + propB;
    }
}

And you don't need to set propC.

like image 176
Roman Doskoch Avatar answered Oct 29 '25 03:10

Roman Doskoch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!