简体   繁体   English

如何建立清单 <FileInfo> 来自IEnumerable <string> ?

[英]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. 例如,URL计数为399。但是当我使用断点并按F11时,我看到文件计数为0。

With new List<FileInfo>(urls.Count()); 使用new List<FileInfo>(urls.Count()); you create an empty list with an expected capacity of 399. Therefore the count of files is 0. 您创建一个空列表,预期容量为399。因此,文件数为0。

The next step is to fill the list with actual FileInfo objects; 下一步是用实际的FileInfo对象填充列表。 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 或与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. 但是,您的示例变量为'urls',因此我怀疑您正在尝试执行比您解释的更多的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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