3

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

Carlos
  • 1,638
  • 5
  • 21
  • 39

2 Answers2

6

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.

Roman
  • 11,966
  • 10
  • 38
  • 47
3

If you're not working with Linq to objects, (i.e. the lambdas are required to be expressions, not method delegates as with Linq to SQL/Entity Framework) you could do this with the help of an anonymous object and two Select statements:

return myList
    .Select(l => new {
        propA = 6,
        propB = 3})
    .Select(x => new myObject{
        propA = x.propA,
        propB = x.propB,
        propC = x.propA + x.propB
    })
    .ToList();
spender
  • 117,338
  • 33
  • 229
  • 351