tags:

views:

99

answers:

2

I have an IEnumerable<Point> and I want to convert it to an IEnumerable<float>.

Can I do this in a single Linq statement?

IEnumerable<float> ConvertToPoints(IEnumerable<Point> points)
{
    List<float> floats = new List<float>();
    foreach(var point in points)
    {
        floats.Add(point.X);
        floats.Add(point.Y);
    }
    return floats;
}
+9  A: 

Yes, you can use SelectMany:

return points.SelectMany(point => new float[] { point.X, point.Y });

Another way that doesn't require LINQ is to use an iterator block:

IEnumerable<float> getPoints(IEnumerable<Point> points)
{
    foreach (Point point in points)
    {
        yield return point.X;
        yield return point.Y;
    }
}
Mark Byers
My immediate response would have been the SelectMany, but that iterator block code looks pretty sweet!
RichK
A: 

FWIW, you can also do the inverse - convert a list of floats to a list of PointF structures (piggybacking off of Mark's answer):

IEnumerable<PointF> AsPointF(this IEnumerable<float> ordinates) 
{ 
    float x;
    float y;

    int i = 0;

    foreach (float f in ordinates) 
    {
      switch (i)
      {
        case 0:
          x = f;
          i++;
        break;
        case 1:
          y = f;
          i = 0;
          yield return new PointF(x, y);
        break;
      }
    }
} 

IEnumerable<float> ordinates = GetOrdinatesFromSomewhere();
IEnumerable<PointF> points = ordinates.AsPointF();
wageoghe