[英]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: 我在C#中有一个
object
,该object
来自使用Interop在Excel中的命名范围中进行读取,看起来像这样:
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: 我想将其转换为
Decimal
:
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. 我想象实现此目的的另一种方法是创建一个遍历两个维并将其转换为
Decimal
或将值设置为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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.