Reputation: 71101
I'm a total newb to LINQ. Here is the code I have so far:
public class Folder
{
public Folder(string path)
{
string[] files = Directory.GetFiles(path);
IList<FileInfo> fis = new List<FileInfo>();
files.SomeMethod(x => fis.Add(new FileInfo(x)));
}
}
What is the correct method name to replace SomeMethod with this to get it to work? I'd basically just like a more concise way of writing a loop here.
Upvotes: 1
Views: 863
Reputation: 12123
There's already a DirectoryInfo method to do this:
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fis = di.GetFileSystemInfos();
If you need it to be a List, use Enumerable.ToList.
Upvotes: 1
Reputation: 41558
sounds like you're looking for something like the ForEach function in List. You could do the following...
files.ToList().ForEach(x => fis.Add(new FileInfo(x)));
or you could do something like this as a more direct approach
IList<FileInfo> fis = (from f in Directory.GetFiles(path)
select new FileInfo(f)).ToList();
or...
IList<FileInfo> fis = Directory.GetFiles(path).Select(s => new FileInfo(s)).ToList();
// or
IList<FileInfo> fis = Directory.GetFiles(path)
.Select(s => new FileInfo(s))
.ToList();
Or - without using any linq at all, how about this one?...
IList<FileInfo> fis = new List<FileInfo>(new DirectoryInfo(path).GetFiles());
Upvotes: 13
Reputation: 50712
string[] files = Directory.GetFiles(path);
IList<FileInfo> fis = new List<FileInfo>();
Array.ForEach(files, x => fis.Add(new FileInfo(x)));
Upvotes: 0
Reputation: 161773
var fis =
new List<FileInfo>(
from f in Directory.GetFiles(path) select new FileInfo(f));
Upvotes: 2
Reputation: 74530
You could use the static ForEach method:
Array.ForEach(x => fis.Add(new FileInfo(x)));
However, you can easily replace the entire function with this one line:
IList<FileInfo> fis = Directory.GetFiles(path).
Select(f => new FileInfo(f)).ToList();
Upvotes: 4