我有一个对象列表。每个对象都包含一个以逗号分隔的字符串形式的类别列表。 我想知道每个类别有多少个对象。为此,我认为我需要按类别分组,然后对条目进行计数 - 但是我无法全神贯注地按列表分组。
using System;
using System.Collections.Generic;
using System.Linq;
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 + " - " + c.amt);
}
// Should return:
// DELIVERY - 4
// DAMAGE - 3
}
}
https://dotnetfiddle.net/bowYb4
上面的示例只是为了演示问题,实际上并没有给出预期的结果。我正在使用来自带有 EF 核心的数据库的数据对象。我知道我尝试做的事情不会转化为 SQL - 我正在做这个客户端,这很好。
最佳答案
一种选择是使用 SelectMany
来展平类别并以键值对的形式转换 dto(我使用值元组来存储它们):
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() });
https://stackoverflow.com/questions/69113916/