簡體   English   中英

選擇不同的名稱並將對象屬性組合到列表中<T>

[英]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類的新對象:_請注意,您還需要分配存在的屬性,而不使用IdTotal新屬性:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM