[英]select distinct name and combine an objects property in a List<T>
我在下面有一个列表,我正在尝试合并T.name属性并总结T.score属性
数据
Name | score
-------------
Jon | 50
Jon | 100
Ash | 100
Ash | 75
所需的结果是
Jon | 150
Ash | 175
我可以在LINQ中执行此操作,并创建具有所需结果的var
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();
问题是我需要x成为List类型,这是HighCharts nuget所需要的。
为什么不创建新课程
public class PieSeriesRenderData
{
public string ID { get; set; }
public int Total { get; set; }
}
然后返回:
List<PieSeriesData> piSeriesData = new List<PieSeriesData>();
var x = piSeriesData.GroupBy(i => i.Name)
.Select(g => new PieSeriesRenderData { Id = g.Key, Total = g.Sum(i => i.Score) })
.ToList();
现在,您将拥有List<PieSeriesRenderData>
对象,可以从Web服务中将其作为Json返回,并将在ajax.successful方法中呈现highchart。
据我从聊天中了解到,您需要输出为List<PieSeriesData>
。 您需要在select
而不是匿名类型中投影PieSeriesData
类的新对象:_请注意,您还需要分配存在的属性,而不使用Id
和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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.