Search code examples
c#objectmultidimensional-array

How can I convert (pass) an object that represents a two dimensional array to a 2-D array variable?


In my C# code I have an object in my code that represents a two dimensional array. I tried to write the value to a file by just converting it to string. I got something like an array but I saw the data was truncated both in the rows and columns.

  var string = obj_1.ToString()

Then I could convert it to a 1-dimensional array with the following code:

  var string_arr = ((IEnumerable)obj_1).Cast<object>()
                               .Select(x => x == null ? x : x.ToString())
                               .ToArray();

But how can I convert this object to a 2-dimensional array? I have to pass all the elements of the object to the related variables.

My extended code looks like this: The object value e.Vqt.Value (from 3.party dll represents a string[m,n]

    public  void subscribe_OPC_items(string ip)
    {
        // Instantiate the client object.
        using (var client = new EasyDAClient())
        {
            client.ItemChanged += client_Main1_ItemChanged;                
            client.SubscribeMultipleItems(
                new[] {                           
                        new DAItemGroupArguments(ip, "OPC.IwSCP.1", "IndraMotion_MTX_P70,System.MessageStore,-1,1,-1,0", 1000, null),
                    });                
        }
    }

    public void client_Main1_ItemChanged(object sender, EasyDAItemChangedEventArgs e)
    {            
        if (e.Succeeded)
        {               
           
            var strings = ((IEnumerable)e.Vtq.Value).Cast<object>()
                               .Select(x => x == null ? x : x.ToString())
                               .ToArray();


        }
    }

Solution

  • If the input is something like a1, a2, a3; b1, b2, b3, i.e. using ; to separate rows, and , to separate values, you could create a 'multidimensional' 2D array like:

    var input = "a1, a2, a3; b1, b2, b3";
    var jagged = input.Split(';').Select(row => row.Split(',')).ToArray();
    
    var rowCount = jagged.Length;
    var columnCount = jagged.First().Length;
    var array2D = new string[rowCount, columnCount];
    for (int i = 0; i < rowCount; i++)
    {
        var row = jagged[i];
        if (row.Length != columnCount) throw new InvalidOperationException("Inconsistent row length");
            for (int j = 0; j < columnCount; j++)
        {
            
            array2D[i, j] = row[j];
        }
    }
    

    As you can see, most of the complexity is in converting from a jagged (arr[][]) representation, to a rectangular 2D representation. This ignores any potential issue with escaping the separators, or handling the actual values.

    Another approach is to use a 1D array to represent your 2D data. This can make serialization trivial, since most serialization libraries handle 1D arrays just fine. You just need to ensure at least the width is also included. Something like

    public class MyArray2D<T>
    {
        public int Width { get; set; }
        public int Height { get; set; }
        public T[] Array { get; set; }
        public T this[int x, int y]
        {
            get => Array[y * Width + x];
            set => Array[y * Width + x] = value;
        }
    }
    

    Note that error checking, constructors, etc have been omitted for simplicity.