Search code examples
linqcsvgroup-concatlinq-group

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


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

Solution

  • 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?