Linq lambda表达式(GROUP_CONCAT / STRING_AGG)中XML PATH和Stuff的等价物是什么?

时间:2015-05-05 05:31:37

标签: sql linq lambda substring for-xml-path

我有一张这样的桌子:

EmployeeId  EmployeeName ItemName
4           Ganesh       Key Board
4           Ganesh       Processor
1           Jignesh      Key Board
1           Jignesh      Mouse
1           Jignesh      Processor
3           Rakesh       Key Board
2           Tejas        Key Board
2           Tejas        Mouse
2           Tejas        Processor

我需要对此进行查询,就好像同一个employeeidemployeename的项目名称不同,我们应该将这些项目分开为“,”。

与下面给出的一样:

EmployeeId  EmployeeName ItemName
1           Jignesh      Key Board, Mouse, Processor
2           Tejas        Key Board, Mouse, Processor
3           Rakesh       Key Board
4           Ganesh       Key Board, Processor

以下是SQL查询: OPs Screen Scrape of STUFF hack which I couldn't OCR

有人可以帮我将上述SQL查询转换为Lambda Expression吗?

1 个答案:

答案 0 :(得分:12)

我假设Lambda expression你的意思是Linq语句(例如EF或Linq2Sql)。

显示的FOR XML PATHSTUFF示例是解决缺乏GROUP_CONCAT or LISTAGG in Sql Server的问题。最后在Sql 2017中有STRING_AGG

您根本不需要在LINQ中重现hack - 而只需将感兴趣的员工的所有行加载到内存中,GroupBy所需的密钥,然后使用{{1在选择投影中:

String.Join

其中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)) }); employeeItemsEmployee之间联接的投影:

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"}
};