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

时间:2009-03-05 12:17:56

标签: linq csv group-concat linq-group

我正在寻找LINQ等效于MySQL的group_concat()

的Sybase LIST()

它会转换:

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

要:

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

6 个答案:

答案 0 :(得分:17)

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

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

答案 1 :(得分:5)

查看此解决方案是否可以帮助您:

List<User> users = new List<User>() 
{ 
    new User {Name = "Bob", Hobby = "Football" },
    new User {Name = "Bob", Hobby = "Golf"},
    new User {Name = "Bob", Hobby = "Tennis"},
    new User {Name = "Sue", Hobby = "Sleeping"},
    new User {Name = "Sue", Hobby = "Drinking"}
};

var groupedUsers = from u in users
         group u by u.Name into g
         select new
         {
             Name = g.First<User>().Name,
             Hobby = g.Select(u => u.Hobby)
         };


foreach (var user in groupedUsers)
{
    Console.WriteLine("Name: {0}", user.Name);
    foreach (var hobby in user.Hobby)
    {
        Console.WriteLine("Hobby: {0}", hobby);
    }
}

答案 2 :(得分:4)

使用以下内容解决问题的_concat方面:

static class EnumerableExtensions 
{  
    public static String AsJoined( this IEnumerable<String> enumerable )
    {
        return AsJoined( enumerable, "," );
    }

    public static String AsJoined( this IEnumerable<String> enumerable, String separator )
    {
        return String.Join( separator, enumerable.ToArray() );
    }
}

bruno conde和Jon Skeet的答案输出foreach可以成为:

Console.WriteLine( "User:\tHobbies");
foreach ( var group in groupedUsers )
    Console.WriteLine( "{0}:\t{1}", group.Key, group.Select( g => g.Hobby ).AsJoined( ", " ) );

...你会得到你要求的精确结果输出格式(是的,我知道其他人已经解决了你的问题,但很难抗拒!)

答案 3 :(得分:3)

否则我们可以执行以下操作 -

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 userList = users.ToList();
                var ug = (from user in users
                          group user by user.User into groupedUserList
                          select new { user = groupedUserList.Key, hobby = groupedUserList.Select(g =>g.Hobby)});

                var ug2 = (from groupeduser in ug
                          select new{ groupeduser.user, hobby =string.Join(",", groupeduser.hobby)});

答案 4 :(得分:2)

在一个Linq声明中执行此操作。我无法推荐代码,但它表明可以完成。

            var groupedUsers = from user in users
                           group user by user.User into userGroup
                           select new
                           {
                               User = userGroup.Key,
                               userHobies =
                                   userGroup.Aggregate((a, b) => 
                                       new { User = a.User, Hobby = (a.Hobby + ", " + b.Hobby) }).Hobby
                           }
                            ;
        foreach (var x in groupedUsers)
        {
            Debug.WriteLine(String.Format("{0} {1}", x.User, x.userHobies));
        }

答案 5 :(得分:-1)

所有答案都不够好;

因为这是一个db查询,但我们所有人都只是在内存中这样做;

diff是内存中的某些操作会发生错误,无法转换为存储表达式;

var list = db.Users.GroupBy(s=>s.User).
             select(g=>new{user=g.Key,hobbys=g.select(s=>s.Hobby)}); // you can just do that from db

var result=list.ToList(); // this is important,to query data to memory;

var result2 = result.select(g=>new{user=g.Key,hobbyes=string.join(",",g.hobbyes)}; //then,do what you love in memory