http://www.codinghelmet.com/ Wear a helmet. Even when coding. Follow Zoran Horvat @zoranh75
hints > linq-array-all-modes

# LINQ Expression to Find All Modes of an Arrayby Zoran Horvat@zoranh75July 30, 2015

Mode of an array is the element which occurs more often than any other element of that array. We can write a LINQ expression which counts occurrences of every element of the array and then pick the element with largest count.

In the previous hint we have developed a LINQ expression which returns array mode ignoring the situation in which more than one element occurs the same number of times. For details, see LINQ Expression to Find Mode of an Array.

In this article, we will extend the same expression so that it returns a collection of numbers which occur equally many times, but more times than any other element of the array.

Below is the function which calculates all modes of a collection of integers.

```IEnumerable<int> AllModes(IEnumerable<int> collection)
{

var pairs =
collection
.GroupBy(value => value)
.OrderByDescending(group => group.Count());

int modeCount = pairs.First().Count();

IEnumerable<int> modes =
pairs
.Where(pair => pair.Count() == modeCount)
.Select(pair => pair.Key)
.ToList();

return modes;

}
```

This time, the function runs in two passes. The first pass is to take all distinct elements of the array and to count occurrences of each of them. In the same step, we are sorting distinct elements descending by their number of occurrences. The result is that all modes of the array will appear at the beginning of the resulting collection.

In the second pass, we are simply taking all the elements from the first collection which have the same count as the most frequent element. All those numbers are modes of the array.

If you are interested in more academic solutions to this same problem, please take a look at the exercise Finding Mode of an Array.

## Demonstration

We can use this function in the context of integer arrays to find their mode. Here is the console application which demonstrates the AllModes function.

```using System;
using System.Collections.Generic;
using System.Linq;

namespace ArrayMode
{

class Program
{

static IEnumerable<int> AllModes(IEnumerable<int> collection)
{

var pairs =
collection
.GroupBy(value => value)
.OrderByDescending(group => group.Count());

int modeCount = pairs.First().Count();

IEnumerable<int> modes =
pairs
.Where(pair => pair.Count() == modeCount)
.Select(pair => pair.Key)
.ToList();

return modes;

}

static void Print(int[] a)
{

for (int i = 0; i < a.Length; i++)
{
Console.Write("{0,3}", a[i]);
if (i < a.Length - 1 && (i + 1) % 10 == 0)
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();

var groups = a
.GroupBy(value => value)
.OrderBy(group => group.Key);

foreach (var group in groups)
{
Console.WriteLine("{0,3} x {1}", group.Key, group.Count());
}

}

static void Main(string[] args)
{

Random rnd = new Random();
int n = 0;

while (true)
{

Console.Write("Array length (0 to exit): ");

if (n <= 0)
break;

int[] a = new int[n];
for (int i = 0; i < a.Length; i++)
a[i] = rnd.Next(9) + 1;

Print(a);

IEnumerable<int> modes = AllModes(a);

string separator = ": ";
Console.Write("Modes");
foreach (int mode in modes)
{
Console.Write("{0}{1}", separator, mode);
separator = ", ";
}
Console.WriteLine();
Console.WriteLine();

}

}

}
}
```

When this application is run, it produces the following output:

```Array length (0 to exit): 10
8  2  4  4  1  7  9  3  2  9

1 x 1
2 x 2
3 x 1
4 x 2
7 x 1
8 x 1
9 x 2
Modes: 2, 4, 9

Array length (0 to exit): 15
8  1  9  3  5  8  8  6  2  4
6  6  1  5  2

1 x 2
2 x 2
3 x 1
4 x 1
5 x 2
6 x 3
8 x 3
9 x 1
Modes: 6, 8

Array length (0 to exit): 42
5  3  3  4  4  5  8  7  1  5
1  2  1  1  3  1  3  1  6  6
5  1  9  8  8  3  6  6  9  3
3  1  8  3  6  5  7  8  7  5
9  4

1 x 8
2 x 1
3 x 8
4 x 3
5 x 6
6 x 5
7 x 3
8 x 5
9 x 3
Modes: 1, 3

Array length (0 to exit): 0
```

Published: Jul 30, 2015; Modified: May 10, 2015

ZORAN HORVAT

Zoran is software architect dedicated to clean design and CTO in a growing software company. Since 2014 Zoran is an author at Pluralsight where he is preparing a series of courses on object-oriented and functional design, design patterns, writing unit and integration tests and applying methods to improve code design and long-term maintainability.

Watch Zoran's video courses at pluralsight.com (requires registration):

Making Your C# Code More Object-Oriented

This course will help leverage your conceptual understanding to produce proper object-oriented code, where objects will completely replace procedural code for the sake of flexibility and maintainability. More...

This course will lead you step by step through the process of developing defensive design practices, which can substitute common defensive coding, for the better of software design and implementation. More...

Tactical Design Patterns in .NET: Creating Objects

This course sheds light on issues that arise when implementing creational design patterns and then provides practical solutions that will make our code easier to write and more stable when running. More...

Tactical Design Patterns in .NET: Managing Responsibilities

Applying a design pattern to a real-world problem is not as straight-forward as literature implicitly tells us. It is a more engaged process. This course gives an insight to tactical decisions we need to make when applying design patterns that have to do with separating and implementing class responsibilities. More...

Tactical Design Patterns in .NET: Control Flow

Improve your skills in writing simpler and safer code by applying coding practices and design patterns that are affecting control flow. More...

Writing Highly Maintainable Unit Tests

This course will teach you how to develop maintainable and sustainable tests as your production code grows and develops. More...

Improving Testability Through Design

This course tackles the issues of designing a complex application so that it can be covered with high quality tests. More...