使用Linq对字符串进行分组,排序和连接 [英] Using Linq to group, order and concatenate strings

查看:220
本文介绍了使用Linq对字符串进行分组,排序和连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据

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

我正在寻找结果

A     HelloWorld
B     FooBar

我正在努力使语法正确无误-我试图使用Aggregate,但是我不确定是否可以(或应该)使用SelectMany

I am struggling to get the syntax quite right - I was trying to use Aggregate, but I wasn't sure if I could (or should) use SelectMany

我将不胜感激.

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

谢谢

西蒙(Simon)

推荐答案

我认为此(C#)应该有效:

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

这篇关于使用Linq对字符串进行分组,排序和连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆