聚集不同ID的Linq

时间:2019-05-30 19:02:05

标签: c# linq linq-query-syntax

对于以下问题,我无法获取正确的Linq查询: 我有一个Storypoint的List <>,其中包含以下数据:

ParentID    TaskID      Points
--------    ------    -----------
    1         100          2
    1         101          1
    1         103          1
    2         102          1
    2         104          4
    3         105          1

我正在寻找一个具有StoryPoints总数的不同ParentID的列表:

ParentID    Count
--------    -----
   1          4
   2          5
   3          1

我已经尝试过此块,但是语法抛出错误:

var storytaskpoints =
                        from u in storypoints
                        group u by u.ParentID into g
                        select new
                        {
                            ParentID = g.Key,
                            Count = (from u in g select u.Points).Count();
                        }

我的StoryTaskPoint类:

class StoryTaskPoint
    {
        public int ParentID { get; set; }
        public int Points { get; set; }
        public int TaskID { get; set; }

        public StoryTaskPoint()
        { }

        StoryTaskPoint(
            int taskID,
            int parentID,
            int points)
        {
            TaskID = taskID;
            ParentID = parentID;
            Points = points;
        }
    }

任何帮助将不胜感激。...

1 个答案:

答案 0 :(得分:1)

 from u in storypoints
                        group u by u.ParentID into g
                        select new
                        {
                            ParentID = g.Key,
                            Count = g.Sum(gg=>gg.Points)
                        }

使用.Sum代替.Count