[英]C# optimal way to populate a List<Class> from List<string>
我有非常簡單的代碼來說明自己。
List<string> Files = new List<string>( Directory.EnumerateFiles(PathLocation));
但是,現在我希望使生活變得復雜,並且有一個文件對象。
public class File
{
public int FileId { get; set; }
public string Filename { get; set; }
}
有沒有一種最佳的方法來填充類的字符串屬性,即有沒有比使用foreach循環或類似方法更好的方法?
您可以使用LINQ Select
替換foreach循環:
List<File> files = Files.Select(s => new File() { FileId = id, Filename = s})
.ToList();
但是無需創建新的List
來優化代碼:
List<File> files = Directory.EnumerateFiles(PathLocation)
.Select(s => new File() { FileId = id, Filename = s})
.ToList();
MSDN在這里
當然:
List<File> Files = Directory.EnumerateFiles(PathLocation).Select(f=> new File { FileId = /*...*/, Filename = f }).ToList();
您可以將Files
的內容映射到List<File>
:
var files = Files.Select(f => new File { Filename = f })
.ToList();
使用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.