Khi bạn sử dụng nhóm bởi LINQ tạo ra một bộ sưu tập mới của các mặt hàng, do đó bạn có hai bộ sưu tập của các mặt hàng.
Dưới đây là một giải pháp cho cả hai vấn đề:
- tổng hợp bất kỳ số lượng các thành viên trong một lần lặp và
- tránh sao chép bộ sưu tập của hàng của bạn
Code:
public static class LinqExtensions
{
/// <summary>
/// Computes the sum of the sequence of System.Double values that are obtained
/// by invoking one or more transform functions on each element of the input sequence.
/// </summary>
/// <param name="source">A sequence of values that are used to calculate a sum.</param>
/// <param name="selectors">The transform functions to apply to each element.</param>
public static double[] SumMany<TSource>(this IEnumerable<TSource> source, params Func<TSource, double>[] selectors)
{
if (selectors.Length == 0)
{
return null;
}
else
{
double[] result = new double[selectors.Length];
foreach (var item in source)
{
for (int i = 0; i < selectors.Length; i++)
{
result[i] += selectors[i](item);
}
}
return result;
}
}
/// <summary>
/// Computes the sum of the sequence of System.Decimal values that are obtained
/// by invoking one or more transform functions on each element of the input sequence.
/// </summary>
/// <param name="source">A sequence of values that are used to calculate a sum.</param>
/// <param name="selectors">The transform functions to apply to each element.</param>
public static double?[] SumMany<TSource>(this IEnumerable<TSource> source, params Func<TSource, double?>[] selectors)
{
if (selectors.Length == 0)
{
return null;
}
else
{
double?[] result = new double?[selectors.Length];
for (int i = 0; i < selectors.Length; i++)
{
result[i] = 0;
}
foreach (var item in source)
{
for (int i = 0; i < selectors.Length; i++)
{
double? value = selectors[i](item);
if (value != null)
{
result[i] += value;
}
}
}
return result;
}
}
}
Dưới đây là cách bạn phải thực hiện tổng kết:
double[] result = m.Items.SumMany(p => p.Total, q => q.Done);
Dưới đây là một ví dụ tổng quát:
struct MyStruct
{
public double x;
public double y;
}
MyStruct[] ms = new MyStruct[2];
ms[0] = new MyStruct() { x = 3, y = 5 };
ms[1] = new MyStruct() { x = 4, y = 6 };
// sum both x and y members in one iteration without duplicating the array "ms" by GROUPing it
double[] result = ms.SumMany(a => a.x, b => b.y);
như bạn có thể nhìn thấy
result[0] = 7
result[1] = 11
Hoặc khi hàng không có định danh duy nhất, bạn có thể viết 'nhóm p bởi p vào g'. – Steven
Điều đó đã làm các trick, mặc dù với một sửa đổi: từ p trong m.Items nhóm p bởi p.Id vào g chọn new {SumTotal = g.Sum (r => r.Total), SumDone = g.Sum (r => r.Done)} – Axarydax
Bạn đã đúng, 'p' đã được sử dụng trong truy vấn. Sửa lỗi. – Steven