using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace MaxAndMinNumberInList
{
static class Program
{
/// <summary>
///
/// </summary>
private static void Main()
{
// Sample 1:
Console.WriteLine("... Sample 1");
var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 16, 17 };
// MAX
Console.WriteLine("MAX=>" + list.Max(z => z));
// MIN
Console.WriteLine("MIN=>" + list.Min(z => z));
// Sample 2:
Console.WriteLine("... Sample 2");
// MAX
Console.WriteLine("MAX=>" + list.Max());
// MIN
Console.WriteLine("MIN=>" + list.Min());
// Sample 3:
Console.WriteLine("... Sample 3");
var list2 = new Dictionary<int, string>
{
{ 1, "One" }, { 2, "Two" }, { 3, "Three" },
{ 4, "Four" },{ 5, "Five" }, { 6, "Six" },
{ 7, "Seven" }, { 8, "Eight" }, { 9, "Nine" }
};
// MAX
Console.WriteLine("MAX=>" + list2.Max(z => z.Key));
// MIN
Console.WriteLine("MIN=>" + list2.Min(z => z.Key));
// Sample 4:
Console.WriteLine("... Sample 4");
// MAX
Console.WriteLine("MAX=>" + list.OrderByDescending(x => x).First());
// MIN
Console.WriteLine("MIN=>" + list.OrderBy(x => x).First());
// Sample 5:
Console.WriteLine("... Sample 5");
// MAX
Console.WriteLine("MAX=>" + Max(list));
// MIN
Console.WriteLine("MIN=>" + Min(list));
// Sample 6:
Console.WriteLine("... Sample 6");
// MAX
Console.WriteLine("MAX=>" + Max2(list.ToArray()));
// MIN
Console.WriteLine("MIN=>" + Min2(list.ToArray()));
// Sample 7:
Console.WriteLine("... Sample 7");
// MAX
Console.WriteLine("MAX=>" + Max2(list.ToArray()));
// MIN
Console.WriteLine("MIN=>" + Min2(list.ToArray()));
}
/// <summary>
/// Sample 5: MAX
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private static int Max(this IEnumerable<int> source)
{
if (source == null)
throw new NullReferenceException("source");
var num1 = 0;
var flag = false;
foreach (var num2 in source)
{
if (flag)
{
if (num2 > num1)
num1 = num2;
}
else
{
num1 = num2;
flag = true;
}
}
if (flag) { return num1; }
throw new NullReferenceException("No Elements");
}
/// <summary>
/// Sample 5: MIN
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private static int Min(this IEnumerable<int> source)
{
if (source == null)
throw new NullReferenceException("source");
var num1 = 0;
var flag = false;
foreach (int num2 in source)
{
if (flag)
{
if (num2 < num1)
num1 = num2;
}
else
{
num1 = num2;
flag = true;
}
}
if (flag) { return num1; }
throw new NullReferenceException("No Elements");
}
/// <summary>
/// Sample 6: MAX
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static int Max2(int[] value)
{
var m = value[0];
return Enumerable.Max(value.Concat(new[] { m }));
}
/// <summary>
/// Sample 6: MIN
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private static int Min2(int[] value)
{
var m = value[0];
return Enumerable.Min(value.Concat(new[] { m }));
}
}
}