Search code examples
c#sql-serverlinqstring-aggregationsql-to-linq-conversion

SQL Server STRING_AGG() : equivalent in Linq


This is my table tbl_emp:

enter image description here

This is the result I need:

enter image description here

In SQL Server 2017, I can use STRING_AGG to get the desired result:

SELECT 
    name, 
    STRING_AGG(email,'') 'email', STRING_AGG(email2,'') 'email2'
FROM
    tbl_emp
GROUP BY 
    name

How can I get the same result in Linq? Any help would be greatly appreciated.


Solution

  • In question not given any information about which ORM you are using, so i try to show one example to this case in linq to objects in c#, not fully solution for question

    String_Agg aggregation function takes a set of values and combines them into a string, using a supplied separator. In LINQ (linq to objects) you may do it by using Group By, i think this example helps you:

    class Program
        {
            static void Main(string[] args)
            {
                var emails = new List<EmailData>() { 
                    new EmailData() {Name="Sam", Email="Email1" },
                    new EmailData() {Name="Sam", Email="Email2" },
                    new EmailData() {Name="Ted", Email="Email3" },
                    new EmailData() {Name="Sam", Email="Email4" },
                    new EmailData() {Name="Sam", Email="Email5" }
                };
                var grouping = emails.GroupBy(x => x.Name);
                foreach (var group in grouping)
                {
                    Console.WriteLine(
                        $"{group.Key}: {string.Join(", ", group.Select(x => x.Email))}");
                }
                Console.ReadKey();
            }
        }
        public class EmailData
        {
            public string Name { get; set; }
            public string Email { get; set; }
        }
    

    Result:

    enter image description here