Skip to content

Instantly share code, notes, and snippets.

@InvaderZim85
Created September 13, 2019 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InvaderZim85/bd459c8fdb362f847f6058636e558750 to your computer and use it in GitHub Desktop.
Save InvaderZim85/bd459c8fdb362f847f6058636e558750 to your computer and use it in GitHub Desktop.
Returns the gap in list of type int
public static List<int> GetGaps(List<int> originalList)
{
// Check if the list is empty
if (originalList == null)
return new List<int>();
// Order the list
originalList = originalList.OrderBy(o => o).ToList();
// Get the first element
var first = originalList.First();
// Get the last element
var last = originalList.Last();
// Get the element count
var count = last - first + 1;
// Create a new range
var rangeList = Enumerable.Range(first, count);
// Get all entries which are in the range list but not in the original list
var gapList = rangeList.Except(originalList).ToList();
// Return the result
return gapList;
// Short variant
// return Enumerable.Range(originalList.First(), originalList.Last() - originalList.First() + 1).Except(originalList).ToList();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment