tags:

views:

304

answers:

5

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.

+12  A: 

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());
Scott Ivey
+4  A: 

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();
casperOne
+2  A: 
var fis =
    new List<FileInfo>(
        from f in Directory.GetFiles(path) select new FileInfo(f));
John Saunders
A: 
string[] files = Directory.GetFiles(path);
IList<FileInfo> fis = new List<FileInfo>();
Array.ForEach(files, x => fis.Add(new FileInfo(x)));
ArsenMkrt
+1  A: 

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.

Joe Chung