我需要获取主题名称和给定主题的次数(计数)。
示例:
Name: John
Topic: X, Y, Z => these are List<string>
Name: Bob
Topic: Y
Name: Suzy
Topic: Y, Z
Should generate output:
X: 1
Y: 3
Z: 2
我已经尝试了这一点,但它没有返回正确的结果:
var result = from r in items
orderby r.Topic
group r by r.Topic
into grp
select new { key = grp.Key, cnt = grp.Count() };
答案 0 :(得分:0)
您可以使用其他from
:
var result = from r in lineItems
from t in r.Topic // List<string>
group t by t into grp
orderby grp.Key
select new { key = grp.Key, cnt = grp.Count() };
答案 1 :(得分:0)
我喜欢使用SelectMany(以展平内部集合) 只是另一种方法来做到这一点
var result = items.SelectMany((w) => w.Topic)
.GroupBy((q) => q)
.Select((p) => new { Grp = p.Key, Cnt = p.Count() })
.OrderBy((g) => g.Cnt);