views:

48

answers:

2

I have something similar to this:

var d1 = new DirectoryInfo(Path.Combine(source, @"bills_save." + dt));
var d2 = new DirectoryInfo(Path.Combine(source, @"reports_save." + dt));

var f1 = d1.GetFiles();
var f2 = d2.GetFiles();

I want to get, and combine, all the filenames into one FileInfo list. Would make my parsing a lot easier. Concat, AddRange, join... nothing seems to work. Most of what I see is for adding 2 lists, arrays.

+5  A: 

Well, Concat certainly should work:

// f3 will be IEnumerable<FileInfo>
var f3 = f1.Concat(f2);

If you need an array or a list, call ToArray or ToList appropriately:

var list3 = f1.Concat(f2).ToList();
var array3 = f1.Concat(f2).ToArray();

By the way, your verbatim string literal doesn't need to be verbatim - it doesn't contain anything which would need escaping.

Jon Skeet
+1: Concat is a simple option, and it reads very well too.
RedFilter
I think I must have had a type or something earlier... I thought I tried this, but now it seems to be working.
WernerCD
about the Verbatim String... I had it done via string math initially (source + @"\subfolder") but stumbled across Path.Combine which is much more graceful :)
WernerCD
+2  A: 

You need to make a List<FileInfo>, like this:

List<FileInfo> files = new List<FileInfo>();
files.AddRange(d1.GetFiles());
files.AddRange(d2.GetFiles());

If you have a collection of DirectoryInfos, you can call SelectMany:

IEnumerable<FileInfo> files = directories.SelectMany(d => d.GetFiles());
SLaks
Good thoughts to ponder. Still trying to wrap my head around LINQ. I like the SelectMany.
WernerCD