Plato
Plato

Reputation: 89

How to declare an array like this

I want this data declared as an array for C#:

file1: data1 [rect1] , data2 [rect2] , data3 [rect3]
file2: data1 [rect1] , data2 [rect2]
file3: data1 [rect1] , data2 [rect2] , data3 [rect3], data4 [rect4]
...

file and data are strings, and rect is Rectangle object

It doesn't have to be an array, but I think array would be the best solution for this.

I need to access the data stored in array.

For example I should be able to read all dataX when I give "file1"..

Also, when I give "file1" and "data1" I should be able to access "rect1"..

Could you explain how I could do this?

Upvotes: 0

Views: 90

Answers (2)

Rotem
Rotem

Reputation: 21917

You could define it as a

Dictionary<string, List<(string Data, Rectangle Rect)>>

    (This syntax uses c# 7.0 tuples)

But in this case, I feel a little more explicit definition will help readability.

class RectData
{
    public string Data;
    public Rectangle Rect;
    public RectData(string data, Rectangle rect) { Data = data; Rect = rect; }
}

And then your data type would be a

Dictionary<string, List<RectData>>

Where the key is the file.

Using a Dictionary assumes that the file keys are distinct. If they are not, you could take it a step further by defining

class FileData
{
    public string File;
    public List<RectData> Data;
}

and then use a

List<FileData>

Update

Initializing could look like

var myData = new Dictionary<string, List<RectData>>()
{
    { file1, new List<RectData> {
         new RectData(data1, rect1),
         new RectData(data2, rect2),
    }},
    { file2, new List<RectData> {
         new RectData(data3, rect3),
         new RectData(data4, rect4),
    }},
}

Upvotes: 5

Mahesh Nepal
Mahesh Nepal

Reputation: 1439

I think what you are looking for is a dictionary. Please refer to this documentation for more information: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2

you can declare the data object as:

Dictionary<string, Dictionary<string, Rectangle>> data;

you can access the rectangle data as:

var rectangle1 = data[file1][data1];

Upvotes: 1

Related Questions