Tuples, Tuples – Returning multiple results from a function (C#)

I have no idea of how many times I had to write a function do discover the minimum and the maximum value of a sequence.

I just love the way I can do it now, using C#.

public static class EnumerableExtensions
{
    public static (T min, T max) MinMax<T>(this IEnumerable<T> source)
        where T : IComparable<T>
    {
        using (var iterator = source.GetEnumerator())
        {
            if (!iterator.MoveNext())
            {
                throw new InvalidOperationException("Cannot find min/max of an empty sequence.");
            }

            var result = (min: iterator.Current, max: iterator.Current);
            while (iterator.MoveNext())
            {
                if (iterator.Current.CompareTo(result.min) < 0) result.min = iterator.Current;
                if (iterator.Current.CompareTo(result.max) > 0) result.max = iterator.Current;
            }
            return result;
        }
    }
}

Pretty nice, right?!

class Program
{
    static void Main(string[] args)
    {
        var sequence = Enumerable.Range(10, 1000000);
        var minmax = sequence.MinMax();
        Console.WriteLine($"Min: {minmax.min} Max: {minmax.max}");
    }
}

That’s it.

Compartilhe este insight:

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

A aquisição de novos clientes é importante para o crescimento. Entretanto, a manutenção dos clientes atuais tende a ser mais...
Time to study again. I just started an online course at the Singularity University. If you could solve one of...
To write parallel code is not a trivial task. There are details to consider and rules to observe. Could you...
No último post, solicitei uma explicação para o resultado da execução do código que segue: using System; using System.Threading.Tasks; using...
I believe that, from time to time, it is interesting to learn a new language or framework that takes us...
Em setembro do ano passado, resolvi assinar a versão digital de um jornal, especializado em economia, de grande circulação no...
Oferta de pré-venda!

Mentoria em
Arquitetura de Software

Práticas, padrões & técnicas para Arquitetura de Software, de maneira efetiva, com base em cenários reais para profissionais envolvidos no projeto e implantação de software.

× Precisa de ajuda?