34

Framework 3.5 で C# を使用しています。Generic List<> を 2 つのプロパティですばやくグループ化しようとしています。この例では、CustomerId、ProductId、および ProductCount のプロパティを持つ注文タイプのリストがあるとします。ラムダ式を使用して、CustomerId と ProductId でグループ化された ProductCounts の合計を取得するにはどうすればよいですか?

4

4 に答える 4

59
var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
                 .Select(group => group.Sum(x => x.ProductCount));
于 2008-12-12T18:43:00.720 に答える
16

このスレッドは非常に古いことに気付きましたが、この構文で苦労したので、追加の調査結果を投稿すると思いました。次のように、1つのクエリで合計とID(foreachなし)を返すことができます。

var sums = Orders
            .GroupBy(x => new { x.CustomerID, x.ProductID })
            .Select(group =>new {group.Key, ProductCount = group.Sum(x => x.ProductCount)});

私がそれを機能させるためのトリッキーな部分は、合計がエイリアス化されなければならないということです、どうやら...

于 2010-05-19T19:59:52.160 に答える
7

または、各合計の ID を取得する場合は、次のようにすることができます。

var customerAndProductGroups =
    from order in Orders
    orderby order.CustomerID, order.ProductID // orderby not necessary, but neater
    group order by new { order.CustomerID, order.ProductID };

foreach (var customerAndProductGroup in customerAndProductGroups)
{
    Console.WriteLine("Customer {0} has ordered product {1} for a total count of {2}",
        customerAndProductGroup.Key.CustomerID,
        customerAndProductGroup.Key.ProductID,
        customerAndProductGroup.Sum(item => item.ProductCount));
}
于 2008-12-14T23:40:20.320 に答える