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

发布于 2024-07-14 18:03:04 字数 322 浏览 12 评论 0原文

我正在寻找相当于 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

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

It'll convert:

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

To:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

苏佲洛 2024-07-21 18:03:04

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

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

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

Here's an example:

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?

他夏了夏天 2024-07-21 18:03:04

看看这个解决方案是否对您有帮助:

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

See if this solution helps you:

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);
    }
}
烟雨凡馨 2024-07-21 18:03:04

关于您问题的 _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( ", " ) );

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

re the _concat aspect of your question, using:

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

The outputting foreach in bruno conde and Jon Skeet's answers can become:

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

... and you'll get the precise result output format you asked for (yes, I know the others have already solved your problem, but its hard to resist!)

向日葵 2024-07-21 18:03:04

或者我们可以执行以下操作 -

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

Or else we can do the following-

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)});
蛮可爱 2024-07-21 18:03:04

在一个 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));
        }

To do it in one Linq Statement. There is no way I'd recommend the code, but it shows that it could be done.

            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));
        }
清引 2024-07-21 18:03:04

所有的答案都不够好;

因为这是一个数据库查询,但我们所有人都只是在内存中执行此操作;

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

all answers is not good enough;

because this is a db query,but all of us do that just in memory;

diff is that some operation in memory will occuce a error can't trans to store expression;

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文