Mitch A
Mitch A

Reputation: 2118

Simplest way to perform grouping/projection using Linq To Objects

I'm getting data from the data layer that I need to transform in the middle tier using Linq To Objects (I don't control that tier of the application). I have to perform a grouping operation using multiple keys followed by a string concatenation on the non key-fields. Given the data below, I want to group by CustomerID and Date, and create a new structure in which only a single row is generated based on the key, and the non key field (in this case Item) gets combined into one string:

    CustomerID  Date         Item
    A          11/1/2001    Bread
    A          11/1/2001        Orange Juice
    A          11/1/2001        Salad Dressing
    B          11/1/2001    Bananas
    C          5/6/2001     Candy
    C          12/8/2005    Candy               


    CustomerID  Date         Item
    A          11/1/2001    Bread
                             Orange Juice
                             Salad Dressing
    B          11/1/2001    Bananas
    C          5/6/2001     Candy
    C          12/8/2005    Candy

Is this possible using the functional style linq syntax or do I have to resort to old-school imperative foreach syntax?

Upvotes: 1

Views: 2066

Answers (2)

Zachary Yates
Zachary Yates

Reputation: 13396

Alternatively:

var results = items
  .GroupBy(i => new { i.Date, i.CustomerID })
  .Select(g => new {
    CustomerID = g.Key.CustomerID,
    Date = g.Key.Date,
    Item = string.Join(", ", g.Select(i => i.Item).ToArray())
  });

Upvotes: 3

dtb
dtb

Reputation: 217411

Something like this?

var result = from item in items
             group item by new { item.Date, item.CustomerID } into g
             select new
             {
                 g.Key.CustomerID,
                 g.Key.Date,
                 Item = string.Join(", ", from i in g select i.Item)
             };

Upvotes: 2

Related Questions