Filling a C # array with multiple values ​​at once

I have an array of structures that looks like this:

    public struct DATA
    {
        public int number;
        public int channel;
        public string filename;
        public string description;
    }
    DATA[] myData = new DATA[12];

I need to fill in a lot of values ​​here, for example myData [0] = {0, 1, "myfile", "TBD"}, etc.

What is the easiest way (in terms of LOC) to populate these 12 structures with data? Would it be easier to use a class instead?

+3
source share
3 answers

Method C does not work for this.

DATA[] myData = new DATA[]{{1,3,"asdasd","asdasd"}, {...

You must install each separate DATA structure.

I suggest adding a constructor

public DATA(int number, int channel, string filename, string description)
{
    this.number = number;
    this.channel = channel;
    this.filename = filename;
    this.description = description;
}

and fill the array using ctor

DATA[] myData = new DATA[]{
    new DATA(1,  3,  "abc",  "def"),
    new DATA(2, 33, "abcd", "defg"),
    ...
};

You can also use a generic list and initialize it this way (.NET 3.5 and later):

List<DATA> list = new List<DATA>()
{
    new DATA(1,  3,  "abc",  "def"),
    new DATA(2, 33, "abcd", "defg")
};
+4
source

You may have a constructor for the structure:

 public struct DATA
    {
        public int number;
        public int channel;
        public string filename;
        public string description;

        public DATA(int theNumber, int theChannel, ...)
        {
           number = theNumber;
           channel = theChannel;
           ...
        }

    }

:

List<DATA> list = new List<DATA>();

list.Add(new DATA(1,2,...));

:

DATA[] data = list.ToArray();
+2

:

 for (int i = 0; i < myData.Length; i++)
 {
    myData[i] = new DATA() { number = i, channel = i + 1, filename = "TMP", description = "TBD"};
 }
0

Source: https://habr.com/ru/post/1789758/


All Articles