What is the equivalent of XML PATH and Stuff in Linq lambda expression (GROUP_CONCAT/STRING_AGG)?
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
Is there a for xml path equivalent in LINQ to SQL?
This is one of those situations where LINQ to SQL does not shine.
This code should be left in the database - it will be easier maintained and most likely will perform better there. Is there a particular reason you want to move this working code out of the database and into your application code? If it were up to me I would leave this code where it is.
Related Topics
Conversion Failed When Converting from a Character String to Uniqueidentifier
Characters That Must Be Escaped in T-Sql
4 Byte Unsigned Int in SQL Server
H2 SQL Database - Insert If the Record Does Not Exist
How to Pass a Parameter to a T-SQL Script
Referencing a Calculated Column in the Where Clause SQL
Sqlite Get Name of Attached Databases
Are There Downsides to Using Prepared Statements
Creating Sumif Function in SQL Server 2012
Why Can't I Group by 1 When It's Ok to Order by 1
Using a Select Statement Within a Where Clause
Does Liquibase Support Dry Run
Passing Lists or Tuples as Arguments in Django Raw SQL
Create SQL Server Table Based on a User Defined Type
Left Inner Join VS. Left Outer Join - Why Does the Outer Take Longer