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:

Este é o primeiro post da série em que vou compartilhar algum conhecimento sobre como desenvolver uma aplicação de verdade...
In this post, let’s talk about how to implement Value Types correctly and improve the performance of your applications. The...
Ontem, dia 25/07/2018, a convite do Canal.NET, compartilhei alguns insights sobre modelagem de microsserviços a partir de processos de negócio....
If you ask me one tip to improve the performance of your applications, it would be: Design your objects to...
A publicação original desse post ocorreu em meu blog, em 2011, e gerou uma bela discussão. Infelizmente, essa publicação não...
Em todos esses anos tenho recebido relatos de desenvolvedores projetando sistemas com belas arquiteturas. Muitos deles tem levantado um bocado de questões...