Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find missing number in a sequence in C#
Set a list.
List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};
Now, get the first and last elements −
int a = myList.OrderBy(x => x).First(); int b = myList.OrderBy(x => x).Last();
In a new list, get all the elements and use the Except to get the missing numbers −
List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList(); List<int> remaining = myList2.Except(myList).ToList();
Let us see the complete code −
Example
using System.Collections.Generic;
using System;
using System.Linq;
public class Program {
public static void Main() {
List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};
Console.WriteLine("Numbers... ");
foreach(int val in myList) {
Console.WriteLine(val);
}
int a = myList.OrderBy(x => x).First();
int b = myList.OrderBy(x => x).Last();
List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();
List<int> remaining = myList2.Except(myList).ToList();
Console.WriteLine("Remaining numbers... ");
foreach (int res in remaining) {
Console.WriteLine(res);
}
}
}
Output
Numbers... 1 2 3 5 8 9 Remaining numbers... 4 6 7
Advertisements