[英]LINQ Sub group results with a single query
我的 model 代表一個國家的計數如下
public class GeoStatsModel
{
public int Id { get; set; } // Country Id
public string Name { get; set; } //Country Name
public int Count { get; set; }
}
一些示例結果如下所示
List<GeoStatsModel> response;
14 UNITED STATES : 6668
23 CANADA : 768
3 MEXICO : 83
4 PUERTO RICO : 19
35 ISRAEL : 1
46 ECUADOR : 1
57 GERMANY : 3
68 NETHERLANDS : 2
9 COSTA RICA : 1
我們可以用 2 個 id 的結果從這個列表中進一步過濾嗎
14 UNITED STATES : 6668
23 CANADA : 768
0 Others : [ Sum of Count from all other conuntries]
國家 ID 14 和 23 的值是不變的,不會改變
我可以將所有其他國家的總和作為
List<int> knownCountries = new List<int> { 14, 13 };
int sum_others = response.Where(g => !knownCountries.Contains(g.Id)).Select(g=>g.Count).Sum();
同樣我可以找到
int sum_US=.
int sum_Canada=..
但是我們可以用任何方式將其編寫為 linq 查詢以將結果組合在單個 go 中
我建議使用命名元組來處理Id
、 Name
和Count
List<GeoStatsModel> response =
...
var result = response
.Select(item => (
id : knownCountries.Contains(item.Id) ? item.Id : 0,
name : knownCountries.Contains(item.Id) ? item.Name : "Others",
value : item.Count
))
.GroupBy(item => (id : item.id, name : item.name),
item => item.value)
.Select(group => (
id : group.Key.id,
name : group.Key.name,
count : group.Sum()
));
讓我們看看result
:
string report = string.Join(Environment.NewLine, result
.Select(item => $"{item.id} {item.name} : {item.count}")
);
Console.Write(report);
我使用元組(int id, string name, int count)
作為最終結果,但也可以返回GeoStatsModel
:
...
.Select(group => new GeoStatsModel() {
Id = group.Key.id,
Name = group.Key.name,
Count = group.Sum()
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.