Computer >> Máy Tính >  >> Lập trình >> C#

Tìm số còn thiếu trong một dãy trong C #

Đặt một danh sách.

List<int> myList = new List<int>(){1, 2, 3, 5, 8, 9};

Bây giờ, lấy phần tử đầu tiên và cuối cùng -

int a = myList.OrderBy(x => x).First();
int b = myList.OrderBy(x => x).Last();

Trong danh sách mới, lấy tất cả các phần tử và sử dụng Ngoại trừ để lấy các số còn thiếu -

List<int> myList2 = Enumerable.Range(a, b - a + 1).ToList();
List<int> remaining = myList2.Except(myList).ToList();

Hãy cho chúng tôi xem mã hoàn chỉnh -

Ví dụ

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);
      }
   }
}

Đầu ra

Numbers...
1
2
3
5
8
9
Remaining numbers...
4
6
7