简体   繁体   English

如何根据C#中的列表创建对象

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

I have named a class "File", where there are some "attributes" as properties.我将一个类命名为“文件”,其中有一些“属性”作为属性。

 class File
    {
        public string Attribute1 { get; set; }
        public string Attribute2 { get; set; }
        public string Attribute3 { get; set; }
        public string Attribute4 { get; set; }

    }

The Text-files that I want to read, contains these "attributes".我想阅读的文本文件包含这些“属性”。 For Example I have read files, and file names are like below:例如我读过文件,文件名如下:

List<string> filenames = new List<string>();
            filenames.Add("A0A01M");
            filenames.Add("A1G4AA");
            filenames.Add("A1L4AR");
            filenames.Add("A1L4AX");
    ...(more than 3000 Files)

How to crate class objects based on this list for each text files, which contains attributes ?!如何根据此列表为每个包含属性的文本文件创建类对象?! I am a little bit confused here!!我在这里有点困惑!!

You can use LINQ :您可以使用LINQ

List<File> files = filenames.Select(CreateFile).ToList();

and a method CreateFile :和方法CreateFile

static File CreateFile(string fileName)
{
    // probably load the file from disc here and extract attributes
    return new File
    {
        Attribute1 = ...,
        Attribute2 = ...,
        ...
    };
}

First add constructor with a id:首先添加带有 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; }

    }

Then on your main method where you get the filename list you can do that: List filenames.... Create a empty list of files:然后在您获取文件名列表的主要方法上,您可以这样做:列出文件名...。创建一个空的文件列表:

List<File> fileList = new List<File>();

Then fill fileList with the other values of the filenames list然后用文件名列表的其他值填充 fileList

filenames.ForEach(filenameID=> fileList.Add(filenameID);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM