简体   繁体   中英

How to convert an Object of Decimals into a Decimal Array in C#

I have an object in C# that comes from reading in a named range in Excel using Interop, and it looks like this:

myObject =
oName.RefersToRange.Value {object[1..1, 1..5]}
((object[,])oName.RefersToRange.Value)[1, 1] 10
((object[,])oName.RefersToRange.Value)[1, 2] 20
((object[,])oName.RefersToRange.Value)[1, 3] 30
((object[,])oName.RefersToRange.Value)[1, 4] 40
((object[,])oName.RefersToRange.Value)[1, 5] 50

I would like to convert this into a Decimal like:

myDecimal = {[10.0], [20.0], [30.0], [40.0], [50.0]}

I'm trying to do this by using the following code:

decimal[,] myDecimal = (decimal[,])myObject

I have also tried:

decimal[,] myDecimal = Convert.ToDecimal(myObject)

and a host of other things, none of which have really worked and all tend to give me errors.

I imagine another way to do this would be to create a method which iterates through the two dimensions and either converts them to Decimal or sets the value to 0.0. That would be okay, but I can't seem to get that to work. Here's what I have (BTW - I know this is sloppy and just to demonstrate my futility in solving this issue):

    public static decimal[,] Convert2dObjectTo2dDecimalArray(object obj)
    {
        decimal[,] result = default(decimal[,]);

        for (int i = 0; i <= obj.SomeUnknownMethodThatCountsElements(0); i++)
        {
            for (int j = 0; i <= obj.SomeUnknownMethodThatCountsElements(1); j++)
            {
                try
                {
                    result[i, j] = Convert.ToDecimal(obj[i, j]);
                }
                catch (Exception)
                {
                    result[i, j] = new decimal(0.0);
                }
            }
        }

        return result;
    }

Any help is greatly appreciated.

BTW - I know my example above is actually a 1-Dimensional set of data but I need to work with 2-Dimensions, I'm just trying to keep the example use case short.

you should be able to do this

object[,] obj = new object[,] { { 1.1, 2.1, 2.3 },{ 3.2, 4.3, 5.4 } };
decimal[,] result = new decimal[obj.GetLength(0), obj.GetLength(1)];

for (int i = 0; i < obj.GetLength(0); i++)
{
    for (int j = 0; j < obj.GetLength(1); j++)
    {
        try
        {
            result[i, j] = Convert.ToDecimal(obj[i, j]);
        }
        catch (Exception)
        {
            result[i, j] = new decimal(0.0);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM