简体   繁体   中英

How can I create a List<FileInfo> from IEnumerable<string>?

private void getTotalBytes(IEnumerable<string> urls)
{
     files = new List<FileInfo>(urls.Count());

For example urls count is 399. But when I'm using a break point and hit F11, I see that the count of files is 0.

With new List<FileInfo>(urls.Count()); you create an empty list with an expected capacity of 399. Therefore the count of files is 0.

The next step is to fill the list with actual FileInfo objects; eg

private void getTotalBytes(IEnumerable<string> urls)
{
    files = new List<FileInfo>(urls.Count());
    foreach (var url in urls)
    {
         files.Add(new FileInfo(url));
    }

or with Linq

private void getTotalBytes(IEnumerable<string> urls)
{
    files = urls.Select(u => new FileInfo(u)).ToList();

To literally answer your question:

var files = new List<FileInfo>();
foreach(var file in myEnumerableStringCollection)
{
    files.Add(new FileInfo(file));
}

However, your example's variable is 'urls' so I suspect you're attempting to do more with this than you explained.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM