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

前端之家收集整理的这篇文章主要介绍了c# – 使用linq获取分组的逗号分隔值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想第三列“项目”与分组的值.
  1. Dictionary<string,int> dic = new Dictionary<string,int>();
  2. dic.Add("a",1);
  3. dic.Add("b",1);
  4. dic.Add("c",2);
  5. dic.Add("d",3);
  6.  
  7. var dCounts =
  8. (from i in dic
  9. group i by i.Value into g
  10. select new { g.Key,count = g.Count()});
  11.  
  12. var a = dCounts.Where(c => c.count>1 );
  13.  
  14. dCounts.Dump();
  15. a.Dump();

代码导致:

  1. Key Count
  2. 1 2
  3. 2 1
  4. 3 1

我想要这些结果:

  1. Key Count Items
  2. 1 2 a,b
  3. 2 1 c
  4. 3 1 d

解决方法

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

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

猜你在找的C#相关文章