简体   繁体   中英

Convert sql to linq with STRING_AGG

convert sql to linq that has STRING_AGG

SELECT
    V.pkid,
    V.[Name] AS VendorName,
    SFTP.SFTP_Paths AS SFTP_Paths
FROM
    dbo.Vendor V
    LEFT OUTER JOIN (
        SELECT
            connected_to,
            STRING_AGG(rootfolder, ', ') AS SFTP_Paths
        FROM
            dbo.FTP
        WHERE
            connected_to_type = 4 -- Vendor
        GROUP BY
            connected_to
    ) SFTP ON v.pkid = SFTP.connected_to
WHERE
    V.active = 1
order by
    V.[name]

This query returns the same sql query result. Instead of STRING_AGG (rootfolder, ',') AS SFTP_Paths I used SFTP_Paths = string.Join(",", b.Select (c => c.rootfolder).ToArray()) for equivalence. The rest of the query is understandable.

var query = vendorList.Join(lstFtp.Where(x => x.connected_to_type == 4).GroupBy(a => a.connected_to)
    .Select(b => new
    {
         connected_to = b.Key,
         SFTP_Paths = b.Select(c => c.rootfolder).ToList()
    }).AsEnumerable()
    .Select(b => new
    {
        connected_to = b.connected_to,
        SFTP_Paths = string.Join(",", b.SFTP_Paths).ToArray()
    }),
    right => right.pkid,
    left => left.connected_to,
    (right, left) => new
    {
        V = right,
        SFTP = left
    }).Where(d => d.V.active == 1)
    .Select(e => new
    {
        pkid = e.V.pkid,
        VendorName = e.V.Name,
        SFTP_Paths = e.SFTP.SFTP_Paths
    })
    .OrderBy(e => e.VendorName).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM