使用 LINQ 将多行连接成单行(CSV 属性) [英] Use LINQ to concatenate multiple rows into single row (CSV property)

查看:24
本文介绍了使用 LINQ 将多行连接成单行(CSV 属性)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找与 Sybase 的 LIST() 或 MySQL 的 group_concat() 等效的 LINQ

I'm looking for the LINQ equivalent to the Sybase's LIST() or MySQL's group_concat()

它会转换:

User  Hobby
--------------
Bob   Football 
Bob   Golf 
Bob   Tennis 
Sue   Sleeping 
Sue   Drinking

致:

User  Hobby
--------------
Bob   Football, Golf, Tennis 
Sue   Sleeping, Drinking

推荐答案

这就是 GroupBy 运算符.您在使用 LINQ to Objects 吗?

That's the GroupBy operator. Are you using LINQ to Objects?

这是一个例子:

using System;
using System.Collections.Generic;
using System.Linq;

public class Test
{
    static void Main()
    {
        var users = new[]
        {
            new { User="Bob", Hobby="Football" },
            new { User="Bob", Hobby="Golf" },
            new { User="Bob", Hobby="Tennis" },
            new { User="Sue", Hobby="Sleeping" },
            new { User="Sue", Hobby="Drinking" },
        };

        var groupedUsers = users.GroupBy(user => user.User);

        foreach (var group in groupedUsers)
        {
            Console.WriteLine("{0}: ", group.Key);
            foreach (var entry in group)
            {
                Console.WriteLine("  {0}", entry.Hobby);
            }
        }
    }
}

这就是分组 - 你能自己管理其余的吗?

That does the grouping - can you manage the rest yourself?

这篇关于使用 LINQ 将多行连接成单行(CSV 属性)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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