某些扩展Directory.GetFiles [英] Directory.GetFiles of certain extension

查看:108
本文介绍了某些扩展Directory.GetFiles的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法简化这​​个LINQ前pression,还是有这样做的更好的办法?

Is there a way to simplify this linq expression, or is there a better way of doing this?

Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
         .Where(s => s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
                     s.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
                     s.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
                     ...);

基本上我想返回特定扩展名的所有文件。不幸的是,这种方法不是很灵活。我宁愿能扩展添加到列表中,并有Directory.GetFiles返回这些扩展。这可能吗?

Basically I want to return all files of a certain extension. Unfortunately, this method isn't very flexible. I'd rather be able to add extensions to a list and have Directory.GetFiles return those extensions. Is that possible?

推荐答案

如果您希望做你的过滤在LINQ,你可以做这样的:

If you would like to do your filtering in LINQ, you can do it like this:

var ext = new List<string> {"jpg", "gif", "png"};
var myFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
     .Where(s => ext.Contains(Path.GetExtension(s));

现在外部包含了允许扩展名列表;您可以根据需要进行灵活的过滤添加或删除项目。

Now ext contains a list of allowed extensions; you can add or remove items as necessary for flexible filtering.

这篇关于某些扩展Directory.GetFiles的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆