设定列表。
List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};
现在,获取第一个和最后一个元素-
int a = myList.OrderBy(x => x).First(); int b = myList.OrderBy(x => x).Last();
在新列表中,获取所有元素并使用Except来获取缺失的数字-
List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList(); List<int> remaining = myList2.Except(myList).ToList();
让我们看完整的代码-
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); } } }
输出结果
Numbers... 1 2 3 5 8 9 Remaining numbers... 4 6 7