0

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?

3
  • 3
    Idiomatically, you would start with defining a class containing data and rect Commented Nov 28, 2018 at 6:40
  • 1
    Have you tried Dictionaries? learn.microsoft.com/en-us/dotnet/api/… Commented Nov 28, 2018 at 6:41
  • 1
    Depending on what you're doing, either use a class, or a Dictionary<string, Dictionary<string, Rectangle>> Commented Nov 28, 2018 at 6:41

2 Answers 2

5

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),
    }},
}
Sign up to request clarification or add additional context in comments.

2 Comments

Declaration with RectData is good enough ( file is key ). How do you fill this as a constant?
@Plato Updated in answer
1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.