這已經被回答了,但其他的答案仍然會做在收集多次迭代(多個呼叫或者創建大量可能很好的中間對象/元組,但是如果不是這樣,那麼您可以創建一個擴展方法(或多個),它以傳統方式進行,但很適合LINQ表達式。
這樣的擴展方法是這樣的:
public static Tuple<int, int> Sum<T>(this IEnumerable<T> collection, Func<T, int> selector1, Func<T, int> selector2)
{
int a = 0;
int b = 0;
foreach(var i in collection)
{
a += selector1(i);
b += selector2(i);
}
return Tuple.Create(a, b);
}
而且你可以使用它像這樣:
public class Stuff
{
public int X;
public int Y;
}
//...
var stuffs = new List<Stuff>()
{
new Stuff { X = 1, Y = 10 },
new Stuff { X = 1, Y = 10 }
};
var sums = stuffs.Sum(s => s.X, s => s.Y);
或者當產品沒有唯一的標識符,你可以用p寫'羣p成g'。 – Steven 2010-03-12 11:30:48
雖然做了修改: from p.m.Items p組通過p.Id轉換爲g select new {SumTotal = g.Sum(r => r.Total),SumDone = g.Sum (r => r.Done)} – Axarydax 2010-03-12 11:33:48
你說得對,在查詢中已經使用了'p'。修復。 – Steven 2010-03-12 11:49:02