Linq:
var array = (from double d in list
select (int)d).ToArray();
Travis Gockel
2010-01-20 18:44:50
Linq:
var array = (from double d in list
select (int)d).ToArray();
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);
}
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; }
);
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];