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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With