John Adams
John Adams

Reputation: 4843

List Generic IEnumerable has some invalid arguments

I'm trying to improve my program which currently builds a generic list of strings as follows:

 List<string> fileList = new List<string>(Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories));

to a different generic list which is hopefully more flexible:

List<InputFileInfo> fileList = List<InputFileInfo>(Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories));

 public class InputFileInfo
{
    public string _fullPath { get; set; }
    public string _Message { get; set; }
    public int _RowCount { get; set; }
    public InputFileInfo(string fName)
    {
        _fullPath = fName;
        _RowCount = 0;
        _Message = String.Empty;
    }
}

Directory.GetFiles returns a string array and I guess my InputFileInfo constructor is not sufficient. Do I need to loop thru a string array and populate List using an .Add method for each element of .GetFiles array or is there a way to populate my new List in one statement like the List of strings?

Upvotes: 0

Views: 399

Answers (4)

Jeff
Jeff

Reputation: 36603

If you're using .NET 3.5 or greater you can use LINQ

Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories).Select(i => new InputFileInfo
(i)).ToList();

Upvotes: 0

dlev
dlev

Reputation: 48606

You could use:

var files = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories);
var fileInfoList = files.Select(x => new InputFileInfo(x)).ToList();

The Select() projects each string onto a corresponding object of your type.

Upvotes: 0

dtb
dtb

Reputation: 217411

You can use the Enumerable.Select Extension Method to convert each string into a InputFileInfo object, and the Enumerable.ToList Extension Method to turn the resulting IEnumerable<InputFileInfo> into a List<InputFileInfo>:

var fileList = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories)
                        .Select(fileName => new InputFileInfo(fileName))
                        .ToList();

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504122

Yes - ideally with LINQ to Objects:

var fileList = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories);
                        .Select(name => new InputFileInfo(name))
                        .ToList();

If you haven't come across LINQ yet, I strongly recommend that you look at it in detail. It's ideal for this sort of thing.

Upvotes: 3

Related Questions