JSON to C# : convert an arraylist of doubles to an array of ints?
I have an arraylist of doubles returned by a JSON library. After the JSON parser's decode method is run, we have this in the C# locals window:
Name Value Type myObj Count=4 object {System.Collections.ArrayList} [0] 100.0 object {double} [1] 244.0 object {double} [2] 123.0 object {double} [3] 999.0 object {double}
My goal is to produce an array of integers from this ArrayList. It would be simple to iterate and do this one value at a time, but I'd like to know how to do it using the bu开发者_JAVA技巧ilt-in converter functionality. I have been reading theads on ConvertAll but I cannot get it to work.
I do not have control of the JSON library so I must begin with the ArrayList.
Thanks
Linq:
var array = (from double d in list
select (int)d).ToArray();
You need to be careful with ArrayList
s because of boxing. Thus:
// list is ArrayList
int[] array = Array.ConvertAll(list.ToArray(), o => (int)(double)o);
Note the cast is framed as (int)(double)
. This first unboxes the boxed double
and then casts to an int
.
To do this in older versions of .NET
// list is ArrayList
int[] array = Array.ConvertAll(
list.ToArray(),
delegate(object o) { return (int)(double)o; }
);
An alternative is
// list is ArrayList
int[] array = Array.ConvertAll(
(double[])list.ToArray(typeof(double)),
o => (int)o
);
Here we do not need an unboxing operation because we have first converted the ArrayList
to an array of unboxed double
s.
To do this in older versions of .NET
// list is ArrayList
int[] array = Array.ConvertAll(
(double[])list.ToArray(typeof(double)),
delegate(double o) { return (int)o; }
);
I would think something like this (with converter):
private void Main()
{
List<Double> lstd = new List<Double>();
lstd.Add(100.0);
lstd.Add(244.0);
lstd.Add(123.0);
lstd.Add(999.0);
List<int> lsti = lstd.ConvertAll(new Converter<double, int>(DoubleToInt));
}
public static int DoubleToInt(double dbl)
{
return (int)dbl;
}
If you want a sample of a working solution using ConvertAll, here's a quick snippet.
public static void testCOnvertAll()
{
List<double> target = new List<double>();
target.Add(2.3);
target.Add(2.4);
target.Add(3.2);
List<int> result = target.ConvertAll<int>(new Converter<double, int>(DoubleToInt));
}
public static int DoubleToInt(double toConvert)
{
return Convert.ToInt32(toConvert);
}
The linq options are cleaner, but if you don't have linq.
//Assuming someValues is your input array and you're sure you don't need to check the types
int[] outputValues = new int[someValues.Count];
for (int i = 0; i < someValues.Count; i++)
outputValues[i] = (int)someValues[i];
精彩评论