LINQ-从Directory.EnumerateFiles中一起选择文件名和文件大小

本文关键字:选择 文件名 文件大小 一起 Directory EnumerateFiles LINQ- | 更新日期: 2023-09-27 18:26:57

下面的LINQ查询为我提供了指定目录中符合where子句的所有文件,在本例中为文件类型和大小。

public static List<string> getFs(string sDir)
{
    var files = Directory.EnumerateFiles(sDir, "*.*", SearchOption.AllDirectories)
        .Where(
            s => ((s.ToLower().EndsWith(".ai")) ||
                  (s.ToLower().EndsWith(".psd") && new FileInfo(s).Length > 10000000) ||
                  (s.ToLower().EndsWith(".pdf") && new FileInfo(s).Length > 10000000)
                 ) 
               )
       .Select(
                 s => s.Replace(sDir, "")
               );   
    return files.ToList();
}

目前已返回文件名。我想让查询同时返回文件名和文件大小,我想知道如何将其合并到选择部分中?

我不确定如何在LINQ查询中选择多个字段,如果有任何指针,我将不胜感激。

谢谢。

LINQ-从Directory.EnumerateFiles中一起选择文件名和文件大小

您可以使用DirectoryInfo class:而不是使用Directory.EnumerateFiles并创建FileInfo

var files = new DirectoryInfo(sDir).GetFiles("*.*", SearchOption.AllDirectories)
    .Where(
        s => ((s.FullName.ToLower().EndsWith(".ai")) ||
                (s.FullName.ToLower().EndsWith(".psd") && s.Length > 10000000) ||
                (s.FullName.ToLower().EndsWith(".pdf") && s.Length > 10000000)
                )
            )
    .Select(
                s => new { FileName = s.FullName.Replace(sDir, ""), Length = s.Length }
            );

通过这种方式,您可以得到所需的内容,但不能从函数中返回结果,因为方法的返回类型不能是匿名类型。您可以创建一个自定义类,也可以使用新的Tuple类:

public static List<Tuple<string, long>> getFs(string sDir)
{
    var files = new DirectoryInfo(sDir).GetFiles("*.*", SearchOption.AllDirectories)
        .Where(
            s => ((s.FullName.ToLower().EndsWith(".ai")) ||
                    (s.FullName.ToLower().EndsWith(".psd") && s.Length > 10000000) ||
                    (s.FullName.ToLower().EndsWith(".pdf") && s.Length > 10000000)
                    )
                )
        .Select(
                    s => new Tuple<string, long>(s.FullName.Replace(sDir, ""), s.Length)
                );
    return files.ToList();
}

方法的用法如下:

foreach( var t in getFs(@"C:''Windows'") )
{
    Console.WriteLine( "File name: {0}, File size: {1}", t.Item1, t.Item2 );
}

使用匿名类型:

类似这样的东西:

.Select(s => new 
{ 
    fileName = s.Replace(sDir, ""), 
    size = new FileInfo(s).Length 
} );

您可以使用匿名类型:

public static List<string> getFs(string sDir)
{
    var files = Directory.EnumerateFiles(sDir, "*.*", SearchOption.AllDirectories)
        .Where(
            s => ((s.ToLower().EndsWith(".ai")) ||
                  (s.ToLower().EndsWith(".psd") && new FileInfo(s).Length > 10000000) ||
                  (s.ToLower().EndsWith(".pdf") && new FileInfo(s).Length > 10000000)
                 ) 
               )
       .Select(
                 s => new { s.Replace(sDir, ""), s.Lenght}
               );   
    return files.ToList();
}