Linq sum inline

Can anything be connected with this?

Essence (with 3 properties)
---> int A
---> int B
---> int C

from record in dbset select new Entity { A = record.AB = record.BC = A * B } 
+4
source share
2 answers

When using object initialization syntax, you can only assign properties to fields available at build time. So you have two options if you want C be computed with A and B You can read these properties with record :

 from record in dbset select new Entity { A = record.AB = record.BC = record.A * record.B } 

More complex situations may make it impossible to repeat the definitions of A and B in this way. For example, repeating a long definition of how these calculations are computed can be costly. It is also harder to read when similar code repeats. In such cases, you may want to have an intermediate selection class that collects the relevant information before the final selection:

 from record in dbset select new { A = someComplicatedFunction(record.A), B = someComplicatedFunction(record.B) } into info select new Entity { A = info.A, B = info.B, C = info.A * info.B } 

Of course, if C always evaluated using A and B , then you can create a getter property as suggested by @ vc74

+3
source

In this particular example, use

 from record in dbset select new Entity { A = record.AB = record.BC = record.A * record.B } 
+4
source

Source: https://habr.com/ru/post/1480542/


All Articles