Grouping the details of the data into one, price field should be separated by semi-colon

I have this requirement that need to group the data into OrderNum, the price needs to be consolidated in one row separated by semi-colon, this was determined by Type. I can do this by Iterating the results but, probably there’s a better way to do it especially in LINQ.

var notebooks = new List<NoteBook>
            {
                new NoteBook { Type = 1, Currency = "USD", Price = 1000, OrderNum = "123" },
                new NoteBook { Type = 2, Currency = "USD", Price = 2000, OrderNum = "123" },
                new NoteBook { Type = 0, Currency = "USD", Price = 3000, OrderNum = "456" },
                new NoteBook { Type = 0, Currency = "USD", Price = 4000, OrderNum = "789" },
                new NoteBook { Type = 4, Currency = "USD", Price = 5000, OrderNum = "753" }

            };

            var results = from r in notebooks
                          group r by new { r.OrderNum } into g
                          select new
                              {
                                  Currency = g.First().Currency,
                                  OrderNum = g.First().OrderNum,
                                  Price = ???
                              };

I’m expecting a result of

Currency OrderNum Price  
USD   123   1000; 2000  
USD   456   3000  
USD   789   4000  
USD   753   5000  


Source: .net

1 Comment

  1. Digin Dominic

    Not sure from your description how Type should be used here, but to form a single price line you can use String.Join:

    Price = String.Join(";", g.Select(x => x.Price))

    And just in case you are running .Net version older than 4.0, make sure to convert second param to an array:

    Price = String.Join(";", g.Select(x => x.Price).ToArray())

    Reply

Leave a Reply