10

我有一个如下列表:

var products = new List<Product>
{
    new Product { Id = 1, Category = "Electronics", Value = 15.0 },
    new Product { Id = 2, Category = "Groceries", Value = 40.0 },
    new Product { Id = 3, Category = "Garden", Value = 210.3 },
    new Product { Id = 4, Category = "Pets", Value = 2.1 },
    new Product { Id = 5, Category = "Electronics", Value = 19.95 },
    new Product { Id = 6, Category = "Pets", Value = 5.50 },
    new Product { Id = 7, Category = "Electronics", Value = 250.0 },
};

我想按类别分组并获得属于该类别的“值”的总和。示例:电子产品:284.95

虽然我可以通过其他方式做到这一点,但我想学习查找的用法。

是否可以在查找中获得这两个值(类别和值)?如果是,我该怎么做?

4

4 回答 4

17

当您从 Lookup 中按键检索时,它的行为就像一个分组,因此您可以执行以下操作:

var productLookup = products.ToLookup(p => p.Category);
var electronicsTotalValue = productLookup["Electronics"].Sum(p => p.Value);
var petsTotalValue = productLookup["Pets"].Sum(p => p.Value);
//etc

var totalValue = products.Sum(p => p.Value);
// I wouldn't use the Lookup here, the line above makes more sense and would execute faster
var alsoTotalValue = productLookup.Sum(grp => grp.Sum(p => p.Value)); 
于 2013-04-18T05:31:09.977 回答
8

您可能想使用ToDictionary()而不是ToLookup

var dict = products
    .GroupBy(p => p.Category)
    .ToDictionary(grp => grp.Key, grp => grp.Sum(p => p.Value));

foreach(var item in dict)
{
    Console.WriteLine("{0} = {1}", item.Key, item.Value);
}
于 2013-04-18T05:34:48.113 回答
2

你不需要一个Lookup. 你可以通过一个查询来做到这一点:

var results =
    from p in products
    group p by p.Category into g
    select new
    {
        Category = g.Key,
        TotalValue = g.Sum(x => x.Value)
    };
于 2013-04-18T05:29:28.380 回答
1
var rez = products.ToLookup(k => k.Category, v => v.Value).Select(k=>new KeyValuePair<string, double>(k.Key, k.Sum()));
于 2018-04-03T17:04:48.010 回答