Reputation: 1828
I'm fairly new to C#. How do you work with multidimensional arrays? I am also using WPF.
To be more clear on my problem, here is what I am trying to do:
I have an array that needs to store about 200 'records' and each record has three fields, which the user has entered using a textbox. So I think this is how you would set the array up:
string[,] Properties = new string[500, 3];
I am going to add a new 'record' to that array every time the user hits a button. I am clueless as to how you would do that. I am sure that I am going to need to set up some sort of counter.
I also am going to have to update and delete values in the array. Any help would be appreciated. Thank-You.
Upvotes: 3
Views: 186
Reputation: 354386
You cannot easily add to an array. The only option you do have is to allocate a new array with another row, copy all the old items and put the new data in the last row.
Likewise for deleting a row: You'd have to move all items after the deleted row “up” and make the array shorter. Which boils down to allocating a new array and copying all items. See above :-)
Generally arrays are a low-level construct and should rarely be used by developers in C#. Especially if you want to model a mutable collection. If you want a mutable collection of things, then use a collection of things, namely List<Thing>
for example. Thing
would be a class containing three properties that make up your records.
The collection classes handle all the common cases like inserting and adding items, removing items at arbitrary positions, etc. Since you mentioned WPF, they also play nicely with the data binding and templating capabilities of WPF which are very powerful tools for displaying data in a UI.
Upvotes: 3
Reputation: 143
You should probably use a list instead
LinkedList<String[]> properties = new LinkedList<String[]>();
and then you can add/delete entries
properties.AddLast({"a","b","c"});
the advantage of using a list over an array is that deleting elements from arbitrary positions is easy :)
Upvotes: 2
Reputation: 39013
I'll sum up what the others have suggested, because you're new at this.
Create a class for your record (this example is rather simplistic):
class MyRecord
{
public string Property1 {get; set; }
public string Property2 { get; set; }
public string Property3 { get; set; }
}
Then create a List of those records:
List<MyRecord> theList;
Use theList.Add
to add a new record to the list.
Upvotes: 4