Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq: Convert IEnumable<double> to IEnumable<string> using helper method

Tags:

c#

linq

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
like image 455
Osiris Avatar asked Nov 16 '10 18:11

Osiris


2 Answers

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);
}
like image 97
Matt Ellen Avatar answered Oct 20 '22 18:10

Matt Ellen


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"));
like image 23
Joel Coehoorn Avatar answered Oct 20 '22 19:10

Joel Coehoorn