0

I am having trouble getting the correct Linq query for the following issue: I have a List<> of storypoints that contains the following data:

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

I'm looking to get a list of distinct ParentIDs with an Aggregate count of StoryPoints:

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

I've tried this block but the syntax is throwing an error:

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

My Class for 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;
        }
    }

Any help would be appreciated....

  • 2
    Pay **utmost** attention to the error message(s) -- don't ignore them -- and where you (mis)placed the semicolon there in your Linq query. The error message you get (as well as Visual Studio's wiggly lines) will point this out to you. Also, `Count = (from u in g select u.Points).Count();` is not doing what you seem to believe it does. Check the documentation for the Linq method [`Count()`](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.count?view=netframework-4.7.1#System_Linq_Enumerable_Count__1_System_Collections_Generic_IEnumerable___0__) to learn what it really does... –  May 30 '19 at 19:08
  • 1
    Possible duplicate of [Linq: GroupBy, Sum and Count](https://stackoverflow.com/questions/16522645/linq-groupby-sum-and-count) – jmoerdyk May 30 '19 at 19:21
  • Hi, and welcome to StackOverflow! Since you have an answer that worked, please mark the answer as accepted by clicking on the little green checkmark in the top-left of the answer. – DeadZone May 30 '19 at 19:52

1 Answers1

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

Use .Sum instead of .Count

AD.Net
  • 13,352
  • 2
  • 28
  • 47