我將一個類命名為“檔案”,其中有一些“屬性”作為屬性。
class File
{
public string Attribute1 { get; set; }
public string Attribute2 { get; set; }
public string Attribute3 { get; set; }
public string Attribute4 { get; set; }
}
我想閱讀的文本檔案包含這些“屬性”。例如我讀過檔案,檔案名如下:
List<string> filenames = new List<string>();
filenames.Add("A0A01M");
filenames.Add("A1G4AA");
filenames.Add("A1L4AR");
filenames.Add("A1L4AX");
...(more than 3000 Files)
如何根據此串列為每個包含屬性的文本檔案創建類物件?!我在這里有點困惑!!
uj5u.com熱心網友回復:
您可以使用LINQ:
List<File> files = filenames.Select(CreateFile).ToList();
和一個方法CreateFile:
static File CreateFile(string fileName)
{
// probably load the file from disc here and extract attributes
return new File
{
Attribute1 = ...,
Attribute2 = ...,
...
};
}
uj5u.com熱心網友回復:
首先添加帶有 id 的建構式:
class File
{
public File(String id){this.ID=id;}
public string ID {get; set;}
public string Attribute1 { get; set; }
public string Attribute2 { get; set; }
public string Attribute3 { get; set; }
public string Attribute4 { get; set; }
}
然后在您獲取檔案名串列的主要方法上,您可以這樣做:列出檔案名...。創建一個空的檔案串列:
List<File> fileList = new List<File>();
然后用檔案名串列的其他值填充 fileList
filenames.ForEach(filenameID=> fileList.Add(filenameID);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345521.html
