繁体   English   中英

具有求和功能和嵌套记录的Linq组

[英]Linq group with sum function and nested records

有一个集合:

List<Tuple<string, string, int>> sales = new List<Tuple<string, string, int>> {
            Tuple.Create("Store 1", "Product 1", 1000),
            Tuple.Create("Store 2", "Product 2", 2000),
            Tuple.Create("Store 3", "Product 3", 1500),
            Tuple.Create("Store 3", "Product 3", 10000)};

我想买那棵树:

Store 1, Product 1, 1000
   Store 1, Product 1, 1000
Store 2, Product 2, 2000
   Store 2, Product 2, 2000
Store 3, Product 3, 11500
   Store 3, Product 3, 1500
   Store 3, Product 3, 10000

我使用此linq查询来构建树:

var group = from sale in sales
        group sale by new { sale.Item1, sale.Item2 } into g
        select new { g.Key.Item1, g.Key.Item2, Sum = g.Sum(e => e.Item3),nestedsales = (from s in g select s) };

和此代码输出:

foreach (var e in group)
{
    Console.WriteLine(e.Item1 + ", " + e.Item2 + ", " + e.Sum);
    foreach(var sale in e.nestedsales )
    {
        Console.WriteLine('\t' + sale.Item1 + ", " + sale.Item2 + ", " + sale.Item3);
    }
}

工作正常! 我只是想知道,这是最佳查询吗? 我的意思是,是否可以在不添加第四字段的情况下构建树-查询结果中的nestedsales

是的,不需要“嵌套销售”:

var group = sales.GroupBy(sale=>new { sale.Item1, sale.Item2 });
foreach (var e in group)
{
    Console.WriteLine(e.Key.Item1 + ", " + e.Key.Item2 + ", " + e.Sum(t=>t.Item3));
    foreach (var sale in e)
    {
        Console.WriteLine('\t' + sale.Item1 + ", " + sale.Item2 + ", " + sale.Item3);
     }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM