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:

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

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:

As an experienced .NET developer, you have to deal with NullReferenceException occurrences every day. Am I right? I firmly believe...
No último post desta série, tratamos da “Lei do Retorno Acelerado”. Sabemos que negócios digitais tem crescimento potencialmente exponencial. Neste...
Em minhas consultorias, quando questionado sobre escalabilidade, recorro sempre ao scale cube, compartilhado no excelente livro “The Art of Scalability”,...
I worked a lot in the last months updating the RavenDB bootcamp to v4.x. My work is done (for a...
Gosto bastante da abordagem de Caitie McCaffrey para explicar sagas. Neste post, me inspiro na linha de raciocínio dela para...
Que nível de otimizações podemos esperar do compilador do C# e do JIT? Neste post, compartilho um pequeno, mas esclarecedor...
× Precisa de ajuda?