gpt4 book ai didi

c# - 合并 2 个 foreach 循环(删除具有特定扩展名的文件)

转载 作者:行者123 更新时间:2023-11-30 21:11:03 24 4
gpt4 key购买 nike

我得到了以下代码:

foreach (string file in Directory.GetFiles(generationDir, "*.xaml")
{
File.Delete(file);
}

foreach (string file in Directory.GetFiles(generationDir, "*.cs")
{
File.Delete(file);
}

我想将这 2 个 foreach 合并到一个循环中?那可能吗 ?我对 lambda 表达式不太满意,所以在这里遇到了困难...

最佳答案

foreach (var file in 
Directory.GetFiles(generationDir, "*.*")
.Where(item => item.EndsWith(".xaml") || item.EndsWith(".cs")))
{
File.Delete(file);
}

对于那些喜欢 ForEach() “sequence operator fake”的人 :)(请在使用前注意 “foreach” vs “ForEach”)

Directory.GetFiles(generationDir, "*.*")
.Where(item => item.EndsWith(".xaml") || item.EndsWith(".cs"))
.ToList()
.ForEach(item => File.Delete(item))

如果您使用的是 .NET Framework v4,则可以使用更高效的 Directory.EnumerateFiles()方法:

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

The returned collection is not cached; each call to the GetEnumerator on the collection will start a new enumeration.

关于c# - 合并 2 个 foreach 循环(删除具有特定扩展名的文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8184921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com