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

前端之家收集整理的这篇文章主要介绍了c# – 使用linq获取分组的逗号分隔值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想第三列“项目”与分组的值.
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

解决方法

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}),传入您的数组键.

猜你在找的C#相关文章