[英]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? 有没有一种最佳的方法来填充类的字符串属性,即有没有比使用foreach循环或类似方法更好的方法?
You can use LINQ Select
to replace foreach loop: 您可以使用LINQ
Select
替换foreach循环:
List<File> files = Files.Select(s => new File() { FileId = id, Filename = s})
.ToList();
But needless to create new List
to optimize your code: 但是无需创建新的
List
来优化代码:
List<File> files = Directory.EnumerateFiles(PathLocation)
.Select(s => new File() { FileId = id, Filename = s})
.ToList();
当然:
List<File> Files = Directory.EnumerateFiles(PathLocation).Select(f=> new File { FileId = /*...*/, Filename = f }).ToList();
You can map the contents of Files
into a List<File>
: 您可以将
Files
的内容映射到List<File>
:
var files = Files.Select(f => new File { Filename = f })
.ToList();
The same using LINQ syntax: 使用LINQ语法也是如此:
var query = from f
in Files
select new File { Filename = f };
var files = query.ToList();
List<File> bigList;
var stringList = bigList.Select(f=>f.Filename);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.