Reputation: 5880
Being new rather new to entity framework, LINQ and C#, I am not sure how to change the value of a variable in a nested list. I am aware that LINQ is not meant to update objects, but I read somewhere that you can do it somehow and that's what I am trying here. I am happy with any solution.
Assume we have two lists, myData
with data of the current month, and myDataBefore
with the same list from the previous month. I want to update myData
. More specifically I want to change (in SQL you would say UPDATE
) the valuePrevMonth
and deltaPercentage
for all 1st-level children inside that list - everything else should remain untouched. I tried the following, but this does not have the desired effect.
var myChildren = myData.SelectMany(x => x.children).ToList();
foreach (var child in myChildren)
{
var valuePrevMonth = myDataBefore.SelectMany(x => x.children)
.Where(x => (x.PositionId == child.PositionId &&
x.SubPositionId == child.SubPositionId))
.Select(x => x.Value).FirstOrDefault();
// now comes the write-back step which I am probably messing up
myData.SelectMany(x => x.children)
.Where(x => (x.PositionId == child.PositionId &&
x.SubPositionId == child.SubPositionId))
.Select(x => {
x.previousValue = valuePrevMonth;
x.deltaPercentage = (x.Value - valuePrevMonth) / valuePrevMonth; // probably some IF-NULL check would not hurt
return x;
}).ToList();
}
The last .Select(..)
is my current understanding how to update these two values of a given child object.
My nested list List<myData>
is of following format (please allow me to use some kind of pseudocode for the definition):
myData
{
int? PositionId
string PositionName
int SubPositionId
string SubPositionName
myObject children
decimal? Value
decimal? previousValue
decimal? deltaPercentage
}
Upvotes: 1
Views: 424
Reputation: 13
My first thought is that your second statement beginning with .SelectMany(x => x.Children)
may be unnecessary; if I'm reading it right, the thing you want to update is already in the child
variable, so you would just do:
child.previousValue = valuePrevMonth;
...
That said, it may matter whether your myObject
type is a struct
or a class
; if it's a struct
, updating its fields will not do what you want, because you would be operating on a copy. To update elements of a List of struct
s, you have to get the updated struct
value that you want (e.g., by setting fields on a copy of the value), and then update the entire list element with list[x] = updatedValue;
.
Upvotes: 1