Linq: convert IEnumable <double> to IEnumable <string> using helper method

I have an IEnumerable <double> I want to convert to an IEnumerable <string>. The problem is that the code below raises the null argument in the select statement. What am I doing wrong?

The actual problem occurs when I try to iterate over the returned IEnumerable <& string ;. GT I get an InvalidCastException. I see in 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);
  }

Ok, I solved my problem. This delayed execution of Linq makes debugging difficult. I actually have a call upstream, which is causing the problem.

ICollection<float> floats; //pretend it holds valid data
ConvertToString(floats.Cast<double>()) //<---This is naughty
+5
3

, .

, null IEnumerable<double> .

P.s. :

private IEnumerable<string> ConvertToString(IEnumerable<double> doubles)
{
   return doubles.Select(ConvertToString);
}
+6

:

doubles.Select(d => d.ToString("0.00"));

- , -:

private IEnumerable<string> ConvertToString(IEnumerable<double> doubles, Func<string, double> convertToString)
{
    return doubles.Select(d => convertToString(d))
}

ConvertToString(doubles, d => d.ToString("0.00"));
+1

You can simply do the conversion as follows:

ver strings = doubles.Select(d => string.Format("{0:0.00}", d));
0
source

All Articles