10

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
Micah B.
  • 1,097
  • 4
  • 13
  • 27

3 Answers3

15
    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.

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • 2
    if we use string.Join, then getting exception like Linq to entities doesn't recognize the string.Join method – reddy39 Dec 01 '17 at 11:00
1

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);
|
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
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())
});
Amy B
  • 108,202
  • 21
  • 135
  • 185
  • It won;t work, cause EF can't recognize a C# method string.Join() – Lab Lab Feb 26 '19 at 20:13
  • @LabLab Original question does not involve EF. If you have a question about EF, go ask it. – Amy B Feb 27 '19 at 02:04
  • Simply put: I can't help it if the Microsoft Data team can't get on board with language _Integration_. They made EF its own extra thing with its own dissonance. We're having a LINQ conversation here, not EF. – Amy B Feb 27 '19 at 02:20