我正在寻找LINQ等效于Sybase的LIST()或MySQL的group_concat()
它会转换:
User Hobby -------------- Bob Football Bob Golf Bob Tennis Sue Sleeping Sue Drinking
至:
User Hobby -------------- Bob Football, Golf, Tennis Sue Sleeping, Drinking
Jon Skeet.. 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); } } } }
这是分组 - 你可以自己管理其余的吗?
这就是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); } } } }
这是分组 - 你可以自己管理其余的吗?
看看这个解决方案是否有助于您
Listusers = new List () { 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 ().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); } }
使用以下方法重新_concat
考虑您的问题:
static class EnumerableExtensions { public static String AsJoined( this IEnumerableenumerable ) { return AsJoined( enumerable, "," ); } public static String AsJoined( this IEnumerable enumerable, String separator ) { return String.Join( separator, enumerable.ToArray() ); } }
在bruno conde中输出的foreach和Jon Skeet的答案可以变成:
Console.WriteLine( "User:\tHobbies"); foreach ( var group in groupedUsers ) Console.WriteLine( "{0}:\t{1}", group.Key, group.Select( g => g.Hobby ).AsJoined( ", " ) );
...,您将获得所需的精确结果输出格式(是的,我知道其他人已经解决了您的问题,但是很难抗拒!)