How do I print out the values after GroupBy()?

Bi-HanNoobSaibot

I have a problem, I am trying to figure out how to print out the value after I am done grouping my array.

I have figured out how to print out the Key of the "object" but how do I print out the value?

I know that it is supposed to look like {key: value}: {1: [1], 2: [2, 2], 3: [3, 3], 4: [4]}.

But I only manage to print out the keys in my code below, => 1-, 2-, 3-, 4- Any advice is greatly appreciated.

public static void figureModeOut(int[] source)
    {
      int[] numbers1 = { 1, 2, 3, 3, 2, 4 };

      var step1 = numbers1.GroupBy(x => x);

      foreach (var item in step1)
      {
        Console.WriteLine("{0} -", item.Key);
      }
}
trashr0x

The returned IGrouping<TKey, TElement> (i.e. each item in step1) itself is the IEnumerable<TElement> containing the sequence of values for any given TKey, so just use string.Join() on each item to print out it's values:

foreach (var item in step1)
{
    Console.WriteLine("{0} - {1}", item.Key, string.Join(",", item));
}

Output:

1 - 1

2 - 2,2

3 - 3,3

4 - 4

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related