Gavin
Gavin

Reputation: 1233

C# optimal way to populate a List<Class> from List<string>

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

Answers (4)

Dennis Traub
Dennis Traub

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

cuongle
cuongle

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

Bartosz
Bartosz

Reputation: 3358

Sure:

List<File> Files = Directory.EnumerateFiles(PathLocation).Select(f=> new File { FileId = /*...*/, Filename = f }).ToList();

Upvotes: 5

zmbq
zmbq

Reputation: 39013

List<File> bigList;
var stringList = bigList.Select(f=>f.Filename);

Upvotes: 1

Related Questions