开发者

Using Linq to group, order and concatenate strings

Suppose I have the following data

Key    ID      Data
A      1       Hello
A      2       World
B      2       Bar
B      1       Foo

I am looking to produce the result

A     HelloWorld
B     FooBar

I am struggling to get the syntax qui开发者_JAVA百科te right - I was trying to use Aggregate, but I wasn't sure if I could (or should) use SelectMany

I'd be grateful of any help.

    Dim data = result.Rows.
                    GroupBy(Function(r) r.Key).
                    Select(Function(g) g.OrderBy(Function(s) s.ID)).
                    Aggregate(New StringBuilder, Function(cur, nxt)                   
                              cur.Append(nxt.First.Data))

Thanks

Simon


I think this (C#) should work:

var data = from r in result.Rows
           group r by r.Item("Key").ToString() into g
           select new {
               g.Key, 
               Joined = string.Join("", g.OrderBy(s => s.Item("ID"))
                                         .Select(s => s.Item("Data")))
           };


Dim result = result.Rows.GroupBy(Function(r) r.Key).Select(Function(g) New With { _
    g.Key, _
    String.Join("", g.OrderBy(Function(r) r.ID)) _
})


Here's an alternative implementation:

var source = new Item[]
{
    new Item { Key = "A", ID = 1, Data = "Hello" },
    new Item { Key = "A", ID = 2, Data = "World" },
    new Item { Key = "B", ID = 2, Data = "Bar" },
    new Item { Key = "B", ID = 1, Data = "Foo" }
};

var results = source
    .GroupBy(item => item.Key)
    .Select(group => group
        .OrderBy(item => item.ID)
        .Aggregate(new Item(), (result, item) =>
            {
                result.Key = item.Key;
                result.Data += item.Data;
                return result;
            }));


You don't want to Aggregate the groups. You want to aggregage the elements of each group unto itself.

If you want the query to do it, then

Dim data = result.Rows
   .GroupBy( )
   .Select(Function(g) g
     .OrderBy( )
     .Aggregate( )
   )

If that anonymous function starts getting too hairy to write, just make a method that accepts an IGrouping<int, Row> and turns it into what you want. Then call it like:

Dim data = result.Rows
   .GroupBy( )
   .Select( myMethod )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜