user15519784
user15519784

Reputation:

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!!

Upvotes: 0

Views: 66

Answers (2)

hesolar
hesolar

Reputation: 709

First add constructor with a 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

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460058

You can use LINQ:

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

and a method CreateFile:

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

Upvotes: 1

Related Questions