user198003
user198003

Reputation: 11151

Adding and replacing elements in C# array

I have to manipulate with some data in C#. My idea is to add them into array. Elements of that array will be (it will be array with 3 elements in it)

12, test11, comment12, comment23
15, test21, comment22, comment23
27, test31, comment32, comment33
... etc

Then, I will need to change ie. element 15 should be changed as

15, test21, comment22A, comment23

Can you help me how to work with this kind of arrays.

Thank you in advance!

Upvotes: 1

Views: 1963

Answers (3)

dgvid
dgvid

Reputation: 26633

I agree completely with the advice in Jon Skeet's answer. In over seven years of professional development in C#, I can't remember having used multidimensional arrays more than once or twice. The language and the .NET framework offer much better alternatives for most of the situations in which we used multidimensional arrays in older languages.

That said, here is how you assign values to an existing array.

First, since your question doesn't specify a data type, let's assume you have declared the array as a multi-dimensional array of strings:

string foo[,] = new string[42, 3];

You would access the second "column," so to speak, of the 15th "row" like this:

foo[15,2] = "comment22A";

You can find quite a bit more information about multidimensional arrays in C# in the C# Programming Guide.

Upvotes: 1

Surjit Samra
Surjit Samra

Reputation: 4662

Agree with Jon Skeet and here is simple implementation

class Program
{
   class MyArrayType
   {
     public int MyInt { get; set; }
     public string Test { get; set; }
     public string Comment1 { get; set; }
     public string Comment2 { get; set; }
     public string Comment3 { get; set; }

   }

  static void Main()
  {

    List<MyArrayType> list = new List<MyArrayType>();
    list.Add(new MyArrayType { MyInt = 1, Test = "test1", Comment1 = "Comment1", Comment2 = "Comment3", Comment3 = "Comment3" });
    // so on

    list[15].MyInt = 15;
    list[15].Comment1 = "Comment";
    // so on
  }

}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499800

It's not clear what the elements of your array really hard - but it does look like there's a certain amount of structure to them. I'd encourage you to encapsulate that structure in a new type - so you might end up with a:

FooBar[] values = ...;
values[15] = new FooBar(15, "test21", "comment22A", "comment23");

or possibly likewise but with a List<T>. Multi-dimensional arrays (or arrays of arrays, come to that) are generally harder to work with than a single collection of some well-encapsulated type. Also, you should at least consider using a higher level abstraction than the array - see Eric Lippert's blog post "arrays considered somewhat harmful" for more details.

If your first value is meant to be an identifier of some kind, you might even want to change it to a Dictionary<int, FooBar> or a KeyedCollection<int, FooBar>.

Upvotes: 5

Related Questions