我有一個物件的串列。每個物件包含一個以逗號分隔的字串的類別串列。 我想知道每個類別中我有多少個物件。為此,我想我需要按類別分組,然后計算條目--但是我無法理解按串列分組的做法。
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class MyDto
{
public string Name { get; set; }
public List<string> Categories => CategoriesString
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList()。
public string CategoriesString { get; set; }
public override string ToString()
{
return Name " 。" CategoriesString。
}
}
public class Program
{
public static void Main()
{
var dtos = new MyDto[] 。
{
new MyDto() { Name = "Dto 1", CategoriesString = "DelivERY"}。
new MyDto() { Name = "Dto 2", CategoriesString = "DELIVERY , DAMAGE" },
new MyDto() { Name = "Dto 3", CategoriesString = "DAMAGE"},
new MyDto() { Name = "Dto 4", CategoriesString = "DAMAGE , DELIVERY" },
new MyDto() { Name = "Dto 5", CategoriesString = "DelIVERY"},
};
var res = dtos.GroupBy(c => c.Categories).Select(c => new { c.Key, amt = c.Count() }) 。
foreach (var c in res)
{
Console.WriteLine(c.Key " - "/span> c.amt)。
}
//應該回傳:。
// DELIVERY - 4
//DAMAGE - 3。
}
}
https://dotnetfiddle.net/bowYb4
上面的例子只是為了證明這個問題,實際上并沒有得到想要的結果。我正在使用來自EF核心資料庫的資料物件。我知道我想做的事情不會轉化為SQL--我在客戶端做這個,這很好。
uj5u.com熱心網友回復:
一種選擇是使用SelectMany來扁平化類別,并將dtos轉化為鍵值對(我使用valu圖元來存盤它們):
var res = dtos
.SelectMany(dto => dto.Categories.Select(c => (Cat: c, dto.Name))
.GroupBy(c => c.Cat)
.Select(c => new { c.Key, amt = c.Count() }) 。
uj5u.com熱心網友回復:
一個替代的解決方案可以是下面的:
var lookup = dtos
.Select(c => c.Categories) //retrieve the already split values[/span]。
.SelectMany(c => c) //flatten the IEnumerable<List<string> to IEnumerable<string>
.ToLookup(c => c, c => c); //group the same values。
foreach (var item in lookup)
{
Console.WriteLine($"{item.Key} - {item.Count()}") 。
GroupBy和ToLookup的區別在于,前者是以延遲的方式執行,而后者是立即執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/310082.html
標籤:
上一篇:重新加載html后HTML javascript保存的查看位置
下一篇:Linq查詢運算式中的空值檢查
