tags:

views:

99

answers:

6

I have two lists of double

List<double> X
List<double> Y

And I have a destination object:

public class PointD 
{
  public double X
  {get;set;}
  public double Y
  {get;set;}
}

How to transform them into a single list?

public static List<PointD> Transform(List<double> X, List<double> Y)
{
}

All the errors checking must be there.

The answer must be in LINQ, sorry for not specifying this earlier!

+7  A: 

Upgrade to .NET 4 and use Enumerable.Zip?

Daniel Pratt
If .NET 4 isn't an option, Eric Lippert also published the source code of Enumerable.Zip on his blog... http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx
stevemegson
+2  A: 
public static List<PointD> Transform(List<double> x, List<double> y)
{
    if (x == null)
        throw new ArgumentNullException("x", "List cannot be null!");

    if (y == null)
        throw new ArgumentNullException("y", "List cannot be null!");

    if (x.Count != y.Count)
        throw new ArgumentException("Lists cannot have different lengths!");

    List<PointD> zipped = new List<PointD>(x.Count);

    for (int i = 0; i < x.Count; i++)
    {
         zipped.Add(new PointD { X = x[i], Y = y[i] });
    }

    return zipped;
}
LukeH
x and y don't have a Length property. Use Count instead
Daniel Dyson
@Daniel, @CAbbot: Oops, fixed!
LukeH
+1  A: 
    public static List<PointD> Transform(List<double> X, List<double> Y)
    {
        if (X == null || X.Count == 0)
        {
            throw new ArgumentException("X must not be empty");
        }
        if (Y == null || Y.Count == 0)
        {
            throw new ArgumentException("Y must not be empty");
        }
        if (X.Count != Y.Count)
        {
            throw new ArgumentException("X and Y must be of equal length");
        }
        var results = new List<PointD>();
        for (int i = 0; i < X.Count; i++)
        {
            results.Add(new PointD { X = X[i], Y = Y[i]});
        }
        return results;
    }
Daniel Dyson
+6  A: 

something like this could fit your needs

Enumerable.Range(0, X.Count).Select(i=>new PointD{X = X[i], Y = Y[i]).ToList()

It assumes X.Count == Y.Count. Otherwise, some checks need to be done

PierrOz
+1  A: 

Here's another solution (using .NET 3.5). Wrap it in a method with the desired error handling. Assuming XList.Count <= YList.Count.

var points = XList.Select((i, j) => new PointD { X = i, Y = YList[j] });
bruno conde
A: 

Here's another 3.5 method using two lists of doubles.

var joined = from item1 in list1.Select((d, index) => new { D = d, Index = index })
             join item2 in list2.Select((d, index) => new { D = d, Index = index })
             on item1.Index equals item2.Index
             select new { X = item1.D, Y = item2.D };
Anthony Pegram