jon.nicholssoftware.com jon.nicholssoftware.com - 1 month ago 9
C# Question

select distinct name and combine an objects property in a List<T>

I have have a List below, and I am trying to combine the T.name property and sum up the T.score property

Data

Name | score
-------------
Jon | 50
Jon | 100
Ash | 100
Ash | 75


Desired result is

Jon | 150
Ash | 175


I am able to do this in LINQ and create a var with the desired results

List<PieSeriesData> PiSeriesData = new List<PieSeriesData>();
var x = PiSeriesData.GroupBy(i => i.Name)
.Select(g => new { Id = g.Key, Total = g.Sum(i => i.Score) })
.ToList();


The issue with that is I need x to be a List type, which is what the HighCharts nuget requires.

Answer

As I understand from the chat you need the output to be a List<PieSeriesData>. You need to project a new object of PieSeriesData class in the select and not of an anonymous type: _See that you also need to assign the properties that exist and not use new ones like Id and Total:

List<PieSeriesData> PiSeriesData = new List<PieSeriesData>();
var x = PiSeriesData.GroupBy(i => i.Name)
                    .Select(g => new PieSeriesData { 
                        Name = g.Key, 
                        Score = g.Sum(i => i.Score) 
                    }).ToList();

// Now x is of type: List<PieSeriesData>