如何在 C# 中基于列表创建对象
How to create objects based on a list in C#
我命名了一个class“文件”,其中有一些“属性”作为属性。
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)
如何根据此列表为每个包含属性的文本文件创建 class 对象?!
我在这里有点困惑!!
您可以使用 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 = ...,
...
};
}
首先添加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);
我命名了一个class“文件”,其中有一些“属性”作为属性。
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)
如何根据此列表为每个包含属性的文本文件创建 class 对象?! 我在这里有点困惑!!
您可以使用 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 = ...,
...
};
}
首先添加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);