小编典典

使用LINQ将多行连接为单行(CSV属性)

sql

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

它将转换为:

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

至:

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

阅读 162

收藏
2021-04-15

共1个答案

小编典典

那就是GroupBy运算符。您是否正在使用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);
            }
        }
    }
}

这就是分组-您可以自己管理其余的吗?

2021-04-15