icsharpcode/NRefactory — pull request #195 by luiscubal (2013-06-21 17:24:39+00:00)
Title: Auto-LINQ Sum()

This action converts a foreach loop to the corresponding LINQ Sum operation (method syntax).

The main highlights are:

Converts loops such as `foreach(int x in intList) result += x;` to `result += intList.Sum();`.
If there is an assignment right before the loop, then that assignment is incorporated in the expression: `int result = 1; foreach (int x in intList) result += x;` is transformed to `int result = 1 + intList.Sum();`

It supports more complex expressions, such as:
* `foreach (int x in intList) if (x > 0) result += x;` to `result += intList.Where(x => x > 0).Sum();`
* `foreach (int x in intList) result += x * 2;` to `result += intList.Sum(x => x * 2);`
* `foreach (int x in intList) if (x > 0) result += x; else result -= x;` to `result += intList.Sum(x => x > 0 ? x : -x);`
* `foreach (int x in intList) result += 1;` to `result += intList.Count();`
* `foreach (int x in intList) { result += x; result += x / 2; }` to `result += intList.Sum(x => x + x / 2);`

The action is disabled if `Enumerable` does not resolve to `System.Linq.Enumerable` (to ensure it is never used when Linq is unavailable).
It works for `+=`, `-=`, `++` and `--` within the loop.
Only one expression can be modified in the loop. So the action is disabled for `foreach (int x in myList) { result1 += x; result2 += x; }`.
Additionally, the action is disabled for nullable types, since `+=` and `Sum` behave differently for null values.