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

What is the equivalent of XML PATH and Stuff in Linq lambda expression (GROUP_CONCAT/STRING_AGG)?

我有这样的 table :

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 查询:

谁能帮我把上面的 SQL 查询转换成 Lambda 表达式?

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

显示的 FOR XML PATHSTUFF 示例是解决缺少 GROUP_CONCAT or LISTAGG in Sql Server. Finally in Sql 2017 there is STRING_AGG

的 hack

您根本不需要在 LINQ 中重现 hack - 相反,只需将感兴趣的员工组的所有行加载到内存中,GroupBy 所需的键,然后使用 String.Join 在 select 投影中:

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

其中 employeeItemsEmployeeItems 之间连接的投影:

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

结果:

1 Ganesh Keyboard,Mouse
2 John   Keyboard