-2

I'm new with using Linq and was wondering how I could print out multiple values of my Mode value. At the minute I can only get 1 value from the Mode but I want it to show multiples ones.

string[] list = TextBox1.Text.Split(new string[] { "," }, 
    StringSplitOptions.RemoveEmptyEntries);
int[] numbers = new int[list.Length];
for (int i = 0; i < numbers.Length; i++)
{
    numbers[i] = Convert.ToInt32(list[i].Trim());
}
int mode = numbers.GroupBy(v => v)
                  .OrderByDescending(g => g.Count())
                  .First()
                  .Key;
Nathan Werry
  • 876
  • 7
  • 18
Swail
  • 1
  • 2

2 Answers2

0

You need to save off the collection before taking the item(s) you want.

string[] list = TextBox1.Text.Split(new string[] { "," }, 
  StringSplitOptions.RemoveEmptyEntries);
IEnumerable<IGrouping<int, int>> modes = list.GroupBy(v => v);
IEnumerable<IGrouping<int, IGrouping<int, int>>> groupedModes = modes.GroupBy(v => v.Count());
var sortedGroupedModes = groupedModes.OrderByDescending(g => g.Key).ToList();

TextBox2.Text = string.Join(" ", sortedGroupedModes[0].Select(x => x.Key)));
Nathan Werry
  • 876
  • 7
  • 18
  • Getting an error: Cannot implicitly convert type 'System.Linq.IOrderedEnumerable to 'System.Collctions.Generic.IEnumerable' when implmenting your changes. – Swail Nov 29 '18 at 15:01
  • I have corrected the errors, sorry. If you want distinct values of the mode in order, then you can add a `.Distinct()` between the `.SelectMany()` and the `.ToList()` – Nathan Werry Nov 29 '18 at 15:22
  • Thanks Nathan you are a star! Finally I was hoping to output the result into a textbox instead of the console: TextBox2.Text = modes.ToString();. What way would I go about this? – Swail Nov 29 '18 at 15:27
  • I am not sure on your format that you need it in the textbox, but if you need it just how your example details then: `TextBox2.Text = modes[0].ToString();` – Nathan Werry Nov 29 '18 at 15:30
-1

You could get all of the groups and just extract those with the highest count (including ties):

var counts = numbers.GroupBy(v => v)
                    .Select(g => g.Key, Count = g.Count())
                    .OrderByDescending(g => g.Count);

var modes = numbers.Where(g => g.Count == counts.First().Count)
                   .Select(g => g.Key);
D Stanley
  • 149,601
  • 11
  • 178
  • 240