How to find the element with minimum occurrences in an array with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

public static class Program 
{
    /// <summary>
    /// Finds the element with the minimum number of occurrences in a sequence.
    /// </summary>
    /// <typeparam name="T">The type of elements in the collection.</typeparam>
    /// <param name="source">The source collection to evaluate.</param>
    /// <returns>
    /// An optional tuple containing the element and its occurrence count, 
    /// or null if the collection is null or contains no elements.
    /// </returns>
    public static Tuple<T, int> MinOccurrence<T>(this IEnumerable<T> source)
    {
        if (source == null) {
            return null;
        }

        // 1. Group items and order by frequency count ascending (Mono/LINQ compatible)
        var minGroup = source
            .Where(item => item != null)
            .GroupBy(item => item)
            .OrderBy(group => group.Count())
            .FirstOrDefault();

        if (minGroup == null) {
            return null;
        }

        return Tuple.Create(minGroup.Key, minGroup.Count());
    }

    public static void Main(string[] args) 
    {
        int[] arr = new int[] {1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3};

        var result = arr.MinOccurrence();

        if (result != null) {
            Console.WriteLine(result.Item1); // Output: 5
        }
        else {
            Console.WriteLine("The array was empty or null.");
        }
    }
}


/*
run:

5

*/

 



answered Sep 25 by avibootz
...