LINQ Dependent Calculation

I use the following template in C #:

IList<foo> x = y.Select(a => new foo { b = Calc1(), c = Calc2() }).ToList(); foreach(foo f in x) { fd = b / c; } 

What I would like to do is:

 IList<foo> x = y.Select(a => new foo { b = Calc1(), c = Calc2() d = b / c; }).ToList(); 

So the question is: how can you modify this template to allow you to assign a value that depends on other values ​​calculated at the time of the assignment?

(Someone will probably indicate that d should be a property that evaluates and returns a value. This is a contrived example. Suppose that the value of d is computed using other values ​​in addition to c and b, which are not available later.)

+4
source share
2 answers

You cannot reuse initialized properties in an initializer.

I like Eric's technique. If the syntax of the query expression is troubling, you can use a fully functional anonymous method.

  List<int> y = new List<int>() { 1, 2, 3, 4 }; var x = y.Select(a => { int b = a + 1; int c = a + 2; int d = b / c; return new { b = b, c = c, d = d }; }); 
+5
source

If you expand this to use the full LINQ syntax:

 IList<foo> x = (from a in y let bq = Calc1() let cq = Calc2() select new foo { b = bq, c = cq, d = bq / cq }).ToList(); 

This will give you what you want.

There was an answer in which you were advised to repeat method calls (i.e. d = Calc1 () / Calc2 ()), but I would recommend against this, given that it is possible that Calc1 () and Calc2 () are expensive operations, and to no avail, performing them twice can have performance implications.

+8
source

All Articles