Reputation: 1233
I have very simple code which explains itself.
List<string> Files = new List<string>( Directory.EnumerateFiles(PathLocation));
However I now wish to make life complicated and I have a file object.
public class File
{
public int FileId { get; set; }
public string Filename { get; set; }
}
Is there an optimal way to populate the string property of the class, ie is there a better way than using a foreach loop or similar?
Upvotes: 0
Views: 1577
Reputation: 51624
You can map the contents of Files
into a List<File>
:
var files = Files.Select(f => new File { Filename = f })
.ToList();
The same using LINQ syntax:
var query = from f
in Files
select new File { Filename = f };
var files = query.ToList();
Upvotes: 4
Reputation: 75306
You can use LINQ Select
to replace foreach loop:
List<File> files = Files.Select(s => new File() { FileId = id, Filename = s})
.ToList();
But needless to create new List
to optimize your code:
List<File> files = Directory.EnumerateFiles(PathLocation)
.Select(s => new File() { FileId = id, Filename = s})
.ToList();
MSDN is here
Upvotes: 5
Reputation: 3358
Sure:
List<File> Files = Directory.EnumerateFiles(PathLocation).Select(f=> new File { FileId = /*...*/, Filename = f }).ToList();
Upvotes: 5