Combining data details into one, the price field should be separated by a semicolon

I have this requirement that you need to group the data in OrderNum, the price should be consolidated in one line, separated by a comma, this was determined by the type. I can do this, iterate over the results, but probably there is a better way to do this, 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 expect a result

Currency OrderNum Price  
USD   123   1000; 2000  
USD   456   3000  
USD   789   4000  
USD   753   5000  
+4
source share
1 answer

Not sure about your description of 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, when you use .Net version older than 4.0, be sure to convert the second parameter to an array:

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

All Articles