使用 linq 获取分组的逗号分隔值
我想要第三列“项目”,其中包含分组的值。
var dic = new Dictionary<string, int>();
dic.Add("a", 1);
dic.Add("b", 1);
dic.Add("c", 2);
dic.Add("d", 3);
var dCounts =
(from i in dic
group i by i.Value into g
select new { g.Key, count = g.Count()});
var a = dCounts.Where(c => c.count>1 );
dCounts.Dump();
a.Dump();
这段代码的结果是:
Key Count
1 2
2 1
3 1
我想要这些结果:
Key Count Items
1 2 a, b
2 1 c
3 1 d
I would like a third column "items" with the values that are grouped.
var dic = new Dictionary<string, int>();
dic.Add("a", 1);
dic.Add("b", 1);
dic.Add("c", 2);
dic.Add("d", 3);
var dCounts =
(from i in dic
group i by i.Value into g
select new { g.Key, count = g.Count()});
var a = dCounts.Where(c => c.count>1 );
dCounts.Dump();
a.Dump();
This code results in:
Key Count
1 2
2 1
3 1
I would like these results:
Key Count Items
1 2 a, b
2 1 c
3 1 d
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
string.Join(",", {array})
,传入您的键数组。Use
string.Join(",", {array})
, passing in your array of keys.您可以使用:
分组创建的结果(值
g
)有一个属性Key
,为您提供密钥,但它也实现了IEnumerable允许您访问组中的各个值。如果您仅返回
g
,那么您可以使用foreach
迭代所有值或使用 LINQ 处理它们。这是一个简单的转储函数来演示这一点:
You can use:
The result created by grouping (value
g
) has a propertyKey
that gives you the key, but it also implementsIEnumerable<T>
that allows you to access individual values in the group. If you return justg
then you can iterate over all values usingforeach
or process them using LINQ.Here is a simple dump function to demonstrate this: