Get grouped comma separated values with linq

こ雲淡風輕ζ 提交于 2020-08-24 06:33:27

问题


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

回答1:


    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)) });

Use string.Join(",", {array}), passing in your array of keys.




回答2:


You can use:

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

The result created by grouping (value g) has a property Key that gives you the key, but it also implements IEnumerable<T> that allows you to access individual values in the group. If you return just g then you can iterate over all values using foreach or process them using LINQ.

Here is a simple dump function to demonstrate this:

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);
|



回答3:


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


来源:https://stackoverflow.com/questions/3239552/get-grouped-comma-separated-values-with-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!