What is the equivalent of XML PATH and Stuff in Linq lambda [removed]GROUP_CONCAT/STRING_AGG)?

后端 未结 1 1861
难免孤独
难免孤独 2020-12-18 01:36

I am having a table like this :

EmployeeId  EmployeeName ItemName
4           Ganesh       Key Board
4           Ganesh       Processor
1           Jignesh           


        
相关标签:
1条回答
  • 2020-12-18 02:00

    I'm assuming by Lambda expression you mean a Linq statement (e.g. to EF or Linq2Sql).

    The FOR XML PATH and STUFF example shown was a hack to workaround the lack of GROUP_CONCAT or LISTAGG in Sql Server. Finally in Sql 2017 there is STRING_AGG

    You don't need to reproduce the hack at all in LINQ - instead, simply load all rows for the set of employees of interest into memory, GroupBy the required key, and then use String.Join in a select projection:

    var result = db.EmployeeItems
          // If you have a filter add the .Where() here ...
          .GroupBy(e => e.EmployeeId)
          .ToList()
          // Because the ToList(), this select projection is not done in the DB
          .Select(eg => new 
           {
              EmployeeId = eg.Key,
              EmployeeName = eg.First().EmployeeName,
              Items = string.Join(",", eg.Select(i => i.ItemName))
           });
    

    Where employeeItems is a projection of the join between Employee and Items:

    var employeeItems = new []
    {
       new EmployeeItem{EmployeeId = 1, EmployeeName = "Ganesh", ItemName = "Keyboard"},
       new EmployeeItem{EmployeeId = 1, EmployeeName = "Ganesh", ItemName = "Mouse"},
       new EmployeeItem{EmployeeId = 2, EmployeeName = "John", ItemName = "Keyboard"}
    };
    

    Result:

    1 Ganesh Keyboard,Mouse
    2 John   Keyboard
    
    0 讨论(0)
提交回复
热议问题