
目标:获取与存储在字符串数组中的扩展名匹配的文件夹和子文件夹中的文件数(Count).扩展数组可以是“.”不是. { “.DAT”,“TXT”,“味精”}
到目前为止我做了什么:当我有“.”在扩展数组中,一切正常:{“.dat”,“.txt”,“.msg”}
我尝试过替换,但它总是返回0.
工作代码(仅当字符串数组中始终带有“.”时):
string[] ext= new string[] { ".txt",".msg",".dat" };totalfilesInTN = Directory.Enumeratefiles(dlg1.Selectedpath,"*.*",SearchOption.AllDirectorIEs) .Count(s => ext.Any(s1 => s1 == Path.GetExtension(s))); 不工作的代码(总是返回0):
string[] ext= new string[] { "txt","dat" };totalfilesInTN = Directory.Enumeratefiles(dlg1.Selectedpath,SearchOption.AllDirectorIEs) .Count(s => ext.Any(s1 => s1 == Path.GetExtension(s).Replace(".","")));@H_419_16@解决方法 Path.GetExtension方法的文档声明返回值为: The extension of the specifIEd path (including the period “.”),or null,or String.Empty.
你的第二段代码剥离了’.’所以没有一个元素会匹配.因此,请使用与扩展列表相反的方式,并确保每个扩展名的开头都有一个’.’然后使用您的第一个代码块.
string[] ext = new string[] {"txt",".dat" } .Select(x => x.StartsWith(".") ? x : "." + x) .ToArray();@H_419_16@ @H_419_16@ 总结 以上是内存溢出为你收集整理的使用LINQ在C#中计算文件数全部内容,希望文章能够帮你解决使用LINQ在C#中计算文件数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)