문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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())
  });
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top