Jonathan Martin
Jonathan Martin

Reputation: 129

Building a list of objects from a list of parameters used to create them in LINQ

What I want to accomplish looks like this (not in linq)

List<FileInfo> InfoList: ... //Already populated.
List<string> fileNames = new List<string>(InfoList.Count);
InfoList.ForEach(s => filesNames.Add(s.Name.ToString()));

The above code I've already written. I want to turn this next part into linq.

List<ZipArchiveEntry> ZipList = new List<ZipArchiveEntry>(InfoList.Count);

for(int i = 0; i < InfoList.Count; i++)
{
     ZipArchiveEntry = archive.CreateEntry(fileNames[i]);
     ZipList.Add(ZipArchiveEntry);
}

So basically, I want to know if you can use the elements of a list as parameters for a function to build a list of objects.

To make a zip archive entry, I need to call the method archive.CreateEntry(filename), and the file names are the elements of a list I've already built.

Upvotes: 1

Views: 778

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

This looks like a normal projection, so Select() is your method:

var ZipList = fileNames.Select(archive.CreateEntry).ToList();

btw, your fileNames list can be easily created like that:

var fileNames = InfoList.Select(s => s.Name.ToString()).ToList();

Upvotes: 4

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

You can create ZipList directly from InfoList:

var ZipList = InfoList.Select(x => archive.CreateEntry(x.Name.ToString()))
                      .ToList();

Upvotes: 2

Related Questions