问题
I need some help using LINQ to filer a list of files based on the file size. I have some code but it's using file.length instead of FileInfo(file).length. I don't know how to implement an object 'FileInfo' in the expression. HELP?
{
IEnumerable<string> result = "*.ini,*.log,*.txt"
.SelectMany(x => Directory.GetFiles("c:\logs", x, SearchOption.TopDirectoryOnly))
;
result = result
.Where(x => (x.Length) > "500000")
;
}
回答1:
You should be able to do something like this.
Using a DirectoryInfo, the GetFiles will return a collection of FileInfo instead of strings.
new DirectoryInfo(@"c:\logs")
.GetFiles("*.ini,*.log,*.txt", SearchOption.TopDirectoryOnly)
.Where(f => f.Length > 500000);
Of course you would always create FileInfo inline if you wanted to.
If you just wanted the filenames back..
IEnumerable<string> results = new DirectoryInfo(@"c:\logs")
.GetFiles("*.ini,*.log,*.txt", SearchOption.TopDirectoryOnly)
.Where(f => f.Length > 500000)
.Select(f => f.FullName);
回答2:
Sorry. Searchpattern can not check up on multiple extensions.
See this article: http://msdn.microsoft.com/en-us/library/aa328752(VS.71,loband).aspx Basicly these are your searchpattern tools:
- "*" Zero or more characters.
- "?" Exactly one character
There is no separator such as "OR", sadly.
You should instead use a regex pattern:
Regex filepattern = new Regex(".log|.txt|.ini");
var test = new DirectoryInfo("C:\\")
.GetFiles("*", SearchOption.TopDirectoryOnly)
.Where(f => f.Length > 0 && filepattern.IsMatch(f.FullName));
To illustrate what Quintin Robinson is talking about:
var dir = new DirectoryInfo("C:\\");
var test = dir
.GetFiles("*.txt", SearchOption.TopDirectoryOnly)
.Concat(dir.GetFiles("*.log", SearchOption.TopDirectoryOnly))
.Concat(dir.GetFiles("*.ini", SearchOption.TopDirectoryOnly))
.Where(f => f.Length > 0);
He believes that GetFiles is heavily optimized and it would be faster - especially with a directory with a lot files. I have not benchmarked it and really don't know which is fastest :)
Both methods works. I have tested them and they give the same result
来源:https://stackoverflow.com/questions/1494602/c-sharp-linq-filter-list-of-files-based-on-file-size