1

There is a collection:

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)};

I'd like to get the tree:

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

I use this linq query to build the tree:

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) };

and this code for output:

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);
    }
}

It works fine! I just wonder, is it optimal query? I mean, is it possible to build the tree without adding fourth field - nestedsales in the result of the query?

ekad
  • 14,436
  • 26
  • 44
  • 46
user2134488
  • 451
  • 5
  • 13
  • Though it is still a valid question for [SO], I'd also like to tell you that there exists http://codereview.stackexchange.com/, that specifically deals with review and improvements of already working code. Though don't [crosspost](http://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu) the same question over multiple StackExchange sites. – Eugene Podskal Feb 28 '16 at 16:11
  • What do you mean by optimizing the "build the tree without adding fourth field"? After having the grouped lists, are you looking for a more efficient way to sum the values other than o(n)? – shay__ Feb 28 '16 at 17:27
  • No, I mean, I am looking for the way to build the tree without "nestedsales" additional field with nested collection. there is an article https://msdn.microsoft.com/en-us/library/bb545971.aspx where in second example showed two level tree and the query is more simple, but I cannot figure out how to do this in my case. – user2134488 Feb 28 '16 at 18:08

1 Answers1

1

Yes , "nestedsales" is not necessary :

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);
     }
 }