Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用LINQ with Action删除旧文件_C#_Linq - Fatal编程技术网

C# 使用LINQ with Action删除旧文件

C# 使用LINQ with Action删除旧文件,c#,linq,C#,Linq,我想做一些像 Action<FileInfo> deleter = f => { if (....) // delete condition here { System.IO.File.Delete(f.FullName); } }; DirectoryInfo di = new DirectoryInfo(_path); di.GetFiles("*.pdf").Select(dele

我想做一些像

Action<FileInfo> deleter = f =>
    {
        if (....) // delete condition here
        {
            System.IO.File.Delete(f.FullName);
        }
    };

DirectoryInfo di = new DirectoryInfo(_path);

di.GetFiles("*.pdf").Select(deleter); // <= Does not compile!
di.GetFiles("*.txt").Select(deleter); // <= Does not compile!
di.GetFiles("*.dat").Select(deleter); // <= Does not compile!
Action deleter=f=>
{
if(..)//在此处删除条件
{
System.IO.File.Delete(f.FullName);
}
};
DirectoryInfo di=新的DirectoryInfo(_路径);
di.GetFiles(“*.pdf”)。选择(deleter);//
或

di.GetFiles(“*.pdf”).ForEach(操作);
公共静态类Hlp
{
静态公共void ForEach(此IEnumerable items,Action)
{
foreach(项目中的var项目)
行动(项目);
}
}
Select()
用于将项目从
TSource
投影到
TResult
。在您的情况下,不需要选择
,因为您没有投影。相反,使用
List
s
ForEach
方法删除文件:

di.GetFiles("*.pdf").ToList().ForEach(deleter);
正如DarkGray所建议的,如果有点不寻常,您可以使用
选择
首先操作文件,然后返回空集合。我建议使用
ForEach
扩展,如下所示:

ForEach
LINQ扩展 由Richard编辑。

我想引起大家对
foreach
vs
foreach
的关注。在我看来,
ForEach
语句应该直接影响传入的对象,在这种情况下确实如此。所以我自相矛盾。哎呀!:)

它不会编译,因为
GetFiles
返回一个
FileInfo
数组,但是
ForEach
是在
List
上定义的,所以中间缺少一个
ToList()
。我没有ForEach方法,可能是最近的.NET版本引入的?ForEach是数组的静态方法或列表的实例方法。不能用这种方式来称呼它。此外,除非枚举了结果可枚举项,否则不会调用Select。文件不会被删除似乎不起作用,也许Panagiotis Kanavos的评论是正确的,他说表达式在枚举之前不会被计算,所以文件不会被删除?指向@AakashM的强制性链接我同意作者的说法“这更难调试”,但我认为这并不是“更难阅读”。
di.GetFiles("*.pdf").ForEach(action); 

public static class Hlp
{
 static public void ForEach<T>(this IEnumerable<T> items, Action<T> action)
 {
   foreach (var item in items)
     action(item);
 }
}
di.GetFiles("*.pdf").ToList().ForEach(deleter);
public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<T> action)
{
    foreach(TSource item in source)
     {
        action(item);
    }
}
Action<FileInfo> deleter = f =>
{
    if (....) // delete condition here
    {
        System.IO.File.Delete(f.FullName);
    }
};

DirectoryInfo di = new DirectoryInfo(_path);
di.GetFiles("*.pdf").ForEach(deleter);