user2318170 user2318170 - 1 month ago 4x
C# Question

LINQ query for setting the value in collection

I am getting the sum of

using below LINQ query

(from item in context.Target.Transaction
where item.Month >= detailsDaily.Month && item.Month <= parameter.Month
select item.ProposalNumber).Sum();

Now I want to set the value
to 0 between these above month as I used for select. Please suggest what should be LINQ query for that?


If you have list of data as below:

var data = context.Target.Transaction
    .Where(m => m.Month >= detailsDaily.Month 
        && m.Month <= parameter.Month)

Then you can find Sum like:

var sum = data.Sum(m => m.ProposalNumber);

And you can set ProposalNumber to 0 like:

data.ForEach(m => m.ProposalNumber = 0);

Note: If you are using Entity Framework (as I suppose you do) this can be expensive operation to load all data if you have too many rows. If you do not have a lot of data and you choose this way to update your data, then you have to call context.SaveChanges() for changes to take place after setting values. You also should make sure that context.Configurations.AutoDetectChangesEnabled is set to true. I recommend using Raw SQL queries in such scenarios rather than this option.