Use LINQ to concatenate multiple rows into single row (CSV property)

后端 未结 6 1276
[愿得一人]
[愿得一人] 2020-11-27 19:42

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

It\'ll convert:

User  Hobby
--------------
Bob   Football 
Bo         


        
6条回答
  •  青春惊慌失措
    2020-11-27 20:11

    re the _concat aspect of your question, using:

    static class EnumerableExtensions 
    {  
        public static String AsJoined( this IEnumerable enumerable )
        {
            return AsJoined( enumerable, "," );
        }
    
        public static String AsJoined( this IEnumerable 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!)

提交回复
热议问题