簡體   English   中英

如何根據C#中的列表創建對象

[英]How to create objects based on a list in C#

我將一個類命名為“文件”,其中有一些“屬性”作為屬性。

 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)

如何根據此列表為每個包含屬性的文本文件創建類對象?! 我在這里有點困惑!!

您可以使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM