public static class MyExtensions
{
/// <summary>
/// Finds the missing numbers in a list.
/// </summary>
/// <param name="list">List of numbers</param>
/// <returns>Missing numbers</returns>
public static IEnumerable<int> FindMissing(this List<int> list)
{
// Sorting the list
list.Sort();
// First number of the list
var firstNumber = list.First();
// Last number of the list
var lastNumber = list.Last();
// Range that contains all numbers in the interval
// [ firstNumber, lastNumber ]
var range = Enumerable.Range(firstNumber, lastNumber - firstNumber);
// Getting the set difference
var missingNumbers = range.Except(list);
return missingNumbers;
}
}
Now you can call the extension method in the following way:
class Program
{
static void Main(string[] args)
{
// List of numbers
List<int> daysOfMonth =
new List<int>() { 6, 2, 4, 1, 9, 7, 3, 10, 15, 19, 11, 18, 13, 22, 24, 20, 27, 31, 25, 28 };
Console.Write("\nList of days: ");
foreach(var num in daysOfMonth)
{
Console.Write("{0} ", num);
}
Console.Write("\n\nMissing days are: ");
// Calling the Extension Method in the List of type int
foreach(var number in daysOfMonth.FindMissing())
{
Console.Write("{0} ", number);
}
}
}