Search code examples
c#fileinfodirectoryinfo

Combine two (or more) FileInfo lists...


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.


Solution

  • 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.