Return two value via tuple from a method - CSharp Language Basics

CSharp examples for Language Basics:Tuple

Description

Return two value via tuple from a method

Demo Code

using System;/*from   w ww  .java  2 s . c  o m*/
using System.Collections.Generic;
using System.Linq;
class MinMax1
{
   static void Main()
   {
      Random rng = new Random();
      var numbers = Enumerable.Range(0, 100).Select(_ => rng.Next(1000));
      var minMax = MinMax(numbers);
      Console.WriteLine($"Minimum: {minMax.min}");
      Console.WriteLine($"Maximum: {minMax.max}");
   }
   static (int min, int max) MinMax(IEnumerable<int> source)
   {
      using (var iterator = source.GetEnumerator())
      {
         if (!iterator.MoveNext())
         {
            throw new InvalidOperationException("Cannot find min/max of an empty sequence");
         }
         int min = iterator.Current;
         int max = iterator.Current;
         while (iterator.MoveNext())
         {
            min = Math.Min(min, iterator.Current);
            max = Math.Max(max, iterator.Current);
         }
         return (min: min, max: max);
      }
   }
}

Result


Related Tutorials