使用linq获取分组的逗号分隔值

时间:2010-07-13 17:06:16

标签: c# linq linq-to-objects grouping

我想要第三列“items”,其中包含已分组的值。

Dictionary<string, int> 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

3 个答案:

答案 0 :(得分:9)

    var dCounts =
        (from i in dic
            group i by i.Value into g
            select new { g.Key, count = g.Count(), Items = string.Join(",", g.Select(kvp => kvp.Key)) });

使用string.Join(",", {array}),传入您的数组键。

答案 1 :(得分:1)

您可以使用:

var dCounts = 
    from i in dic 
    group i by i.Value into g 
    select new { g.Key, Count = g.Count(), Values = g }; 

通过分组(值g)创建的结果具有一个属性Key,可以为您提供密钥,但它还实现了IEnumerable<T>,允许您访问组中的各个值。如果只返回g,则可以使用foreach迭代所有值,或使用LINQ处理它们。

这是一个简单的转储函数来演示:

foreach(var el in dCounts) {
  Console.Write(" - {0}, count: {1}, values:", el.Key, el.Count);
  foreach(var item in el.Values) Console.Write("{0}, ", item);
|

答案 2 :(得分:0)

from i in dic 
group i.Key by i.Value into g 
select new
{
  g.Key,
  count = g.Count(),
  items = string.Join(",", g.ToArray())
});