如何在Linq中进行此查询?

时间:2019-03-18 13:15:41

标签: c# .net sql-server linq

我有一个数据库中的路径列表。

\\apollon\HardDev\01_Elektronik\Stüliaktualisierung_SAP_Vault\APP_XY4-100_FEX\Version 10
\\apollon\Sales\Kunden\S\SMS Elotherm_Remscheid\Auftrag 3061_Laserschutzbrille_2011-04-05
\\apollon\HardDev\02_Optik\Optik\ZEMAX_Projekte_Salb\TriboLas3D
\\apollon\Sales\Kunden\O\Osram_Regensburg\Auftrag 2002_2008-09-09
\\apollon\Sales\Kunden\H\Horn Glass Industries_Ploessberg\Auftrag 4534_2013-07-26
\\apollon\User\Slunecko\quickies_2016\BSI_screenshots\Neuer Ordner
\\apollon\Sales\Kunden\G\Giesecke&Devrient\Auftrag 2153_2009-06-24
\\apollon\HardDev\01_Elektronik\Stüliaktualisierung_SAP_Vault\AFEM_V12\bestuecker_afem_v12
\\apollon\User\Slunecko\quickies_2015\src_Bosch\BOSCH
\\apollon\Sales\Kunden\H\Hakuto_Japan\4352IO_2013-06-07
etc.

现在,我需要一个将路径作为参数的查询,并且只向我返回直接子文件夹以及其中是否有子文件夹。

示例:

函数获取路径

\\apollon\User\Walzenbach

因此,我想知道该路径具有以下子文件夹

{dir = "\\apollon\User\Walzenbach\docs", subfolderCount = 2}
{dir = "\\apollon\User\Walzenbach\doku", subfolderCount = 0}
{dir = "\\apollon\User\Walzenbach\backup", subfolderCount = 10}

这意味着文件夹docs有2个子文件夹,文件夹doku没有子文件夹,而备份有10个子文件夹。

SQL将朝着这个方向发展。但是我也不确定这是否是最好的SQL查询,我在Linq中也需要它

预先感谢您的帮助

3 个答案:

答案 0 :(得分:1)

考虑使用DirectoryInfo.EnumerateDirectories

string directoryName = "\\apollon\User\Walzenbach"
DirectoryInfo directory = new DirectoryInfo(directoryName);
// TODO: exception if !directory.Exists;

var result = directory.EnumerateDirectories()
    .Select(subDirectory => new
    {
        SubDirectory = subDirectory,       // This is a DirectoryInfo

        // if you prefer the name, instead of the Directory:
        SubDirectoryName = subDirectory.Name,

        // count the number of subfolders of this subfolder:
        SubFolderCount = subFolder.EnumerateDirectories().Count(),
    });

简单的漫画卓悦!

答案 1 :(得分:1)

这是一个建议:

var query=from d in directories
          join sf in directories on d.Path equals sf.ParentPath into grp1
          from sf in grp1.DefaultIfEmpty()
          let result=new {dir=d,sub=sf}
          where reault.dir.Path.StartsWith(path)
          group result by result.dir.Path into grp2
          select new {dir=grp2.Key,subFolderCount=grp2.Count()};

答案 2 :(得分:0)

所以现在我有一个SQL,至少可以合理地执行我想要的操作...但是Linqer无法将其转换为Linq

SELECT [Directory], subfolderCount = 
    (SELECT COUNT([Directory])
    FROM [ArgesPerm].[argarm].[dirs]
    WHERE lower([Directory]) LIKE '\\apollon\user\walzenbach\%'
    GROUP BY [Directory])
FROM [ArgesPerm].[argarm].[dirs]
WHERE lower([Directory]) LIKE '\\apollon\user\walzenbach\%'
AND LEN(SUBSTRING([Directory], 3, 10000)) - Len(Replace(SUBSTRING([Directory], 3, 10000), '\', '')) < 3
GROUP BY [Directory]
ORDER BY [Directory]