http://www.codinghelmet.com/  

Wear a helmet. Even when coding.

hints > linq-array-mode

LINQ Expression to Find Mode of an Array
by Zoran Horvat @zoranh75

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.

Below is the function which calculates mode of a collection of integers.

int Mode(IEnumerable<int> collection)
{
    return
        collection
            .GroupBy(value => value)
            .OrderByDescending(group => group.Count())
            .Select(group => group.Key)
            .First();
}

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 Mode function.

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

namespace ArrayMode
{

    class Program
    {

        static int Mode(IEnumerable<int> collection)
        {
            return
                collection
                    .GroupBy(value => value)
                    .OrderByDescending(group => group.Count())
                    .Select(group => group.Key)
                    .First();
        }

        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): ");
                n = int.Parse(Console.ReadLine());

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

                int mode = Mode(a);

                Console.WriteLine("Mode = {0}", mode);

                Console.WriteLine();

            }

        }

    }
}

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

Array length (0 to exit): 10
  5  7  2  4  9  5  9  7  6  1

  1 x 1
  2 x 1
  4 x 1
  5 x 2
  6 x 1
  7 x 2
  9 x 2
Mode = 5

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

  1 x 1
  2 x 2
  3 x 3
  4 x 1
  5 x 2
  6 x 3
  7 x 1
  8 x 2
Mode = 3

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

  1 x 5
  2 x 7
  3 x 3
  4 x 7
  5 x 2
  6 x 7
  7 x 4
  8 x 6
  9 x 1
Mode = 2

Array length (0 to exit): 0

See also:

Published: Jul 28, 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.

Follow him on Twitter @zoranh75 to receive updates and links to new articles.

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

Advanced Defensive Programming Techniques

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

Share this article

webmasters