I have an IEnumerable<double> I want to convert to an IEnumerable<string>. The problem is the code below throws an argument null exception on the select statement. What am I doing wrong?
The actual problem occurs when I try to iterate through the returned IEnumerable<string>. I get an InvalidCastException. I see in the debuger that strings = {System.Linq.Enumerable.WhereSelectEnumerableIterator<double,string>}
private IEnumerable<string> ConvertToString(IEnumerable<double> doubles)
{
IEnumerable<string> strings = null;
if (doubles != null)
strings = doubles.Select(d => ConvertToString(d));
return strings;
}
private string ConvertToString(double d)
{
return string.Format("{0:0.00}", d);
}
Okay, I solved my problem. This Linq delayed execution makes debugging tricky. I actually have a call upstream causing the problem.
ICollection<float> floats; //pretend it holds valid data
ConvertToString(floats.Cast<double>()) //<---This is naughty
I have tried your code and I do not get an error.
That implies that you are passing a null IEnumerable<double>
into your method.
P.s. You can shorten your method to this:
private IEnumerable<string> ConvertToString(IEnumerable<double> doubles)
{
return doubles.Select(ConvertToString);
}
Why not just:
doubles.Select(d => d.ToString("0.00"));
Or for some real fun that should accomodate your business logic:
private IEnumerable<string> ConvertToString(IEnumerable<double> doubles, Func<string, double> convertToString)
{
return doubles.Select(d => convertToString(d))
}
ConvertToString(doubles, d => d.ToString("0.00"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With