将两个列表转换为一个不同的列表

时间:2010-04-13 15:29:05

标签: c# linq

我有两个double

列表
List<double> X
List<double> Y

我有一个目标对象:

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

如何将它们转换为单个列表?

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

所有错误检查必须在那里。

答案必须在LINQ中,抱歉不提前说明这一点!

6 个答案:

答案 0 :(得分:7)

升级到.NET 4并使用Enumerable.Zip

答案 1 :(得分:6)

这样的事情可以满足您的需求

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

它假设X.Count == Y.Count。否则,需要进行一些检查

答案 2 :(得分:2)

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;
}

答案 3 :(得分:1)

    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;
    }

答案 4 :(得分:1)

这是另一个解决方案(使用.NET 3.5)。将其包装在具有所需错误处理的方法中。假设XList.Count <= YList.Count

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

答案 5 :(得分:0)

这是使用两个双打列表的另一个3.5方法。

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 };