如何有条件地对两个列表的字段求和

时间:2013-07-24 11:24:16

标签: c# .net

我需要对两个列表的X和Y字段求和,但第一个Id等于第二个Id。

我的代码:

//Program.cs

//(...)

class Point
{
    public int Id { get; set; }
    public int X { get; set; }
    public int Y { get; set; }

    public Point(int _Id, int _X, int _Y)
    {
        Id = _Id;
        X = _X;
        Y = _Y;
    }
}

//(...)

List<Point> points = new List<Point>();
List<Point> sumsXY = new List<Point>();

//sum the X and Y of two lists, but points.Id must equal to sumsXY.Id
for (int i = 0; i < objcount; i++)
{
    sumsXY[points[i].Id].X = sumsXY[points[i].Id].X + points[i].X;
    sumsXY[points[i].Id].Y = sumsXY[points[i].Id].Y + points[i].Y;
}

需要帮助。

大卫

3 个答案:

答案 0 :(得分:1)

你在找这样的东西吗?

var sumsXY = points.GroupBy(x => x.Id)
                   .Select(g => new Point(g.Key, g.Sum(x => x.X),
                                          g.Sum(x => x.Y)))
                   .ToList();

将所有具有相同ID的点组合在一起,并为每个组创建一个新点,其中包含该组的ID以及该组中所有点的X和Y值之和。

此答案假定此操作开始时sumsXY为空。如果不是这种情况,您可能希望澄清您的问题并提供样本输入和预期输出。

答案 1 :(得分:1)

List<Point> newList = new List<Point>();
foreach(Point p in points)
{
  Point sumsXYPoint = sumsXY.FirstOrDefault(sums => sums.Id == p.Id);
  if (sumsXYPoint != null)
  {
    newList.Add(new Point() { Id = p.Id, X = sumsXYPoint.X + p.X, Y = sumsXYPoint.Y + p.Y);
  }
}

答案 2 :(得分:1)

这样的事情对你有用:

List<Point> points = new List<Point>();
List<Point> sumsXY = new List<Point>();

points.Add(new Point(1, 10, 10));
points.Add(new Point(2, 10, 20));
points.Add(new Point(3, 10, 30));

sumsXY.Add(new Point(1, 100, 100));
sumsXY.Add(new Point(5, 10, 20));
sumsXY.Add(new Point(6, 10, 30));

foreach (Point p in points)
{
     foreach (Point s in sumsXY)
     {
         if (s.Id == p.Id)
         {
             s.X += p.X;
             s.Y += p.Y;
         }
     }
 }

给出:

  • 110 110
  • 10 20
  • 10 30
相关问题