C# 程式列出兩個列表之間的差異


要獲得兩個列表之間的差異,首先在 C# 中設定兩個列表- 

// first list
List < string > list1 = new List < string > ();
list1.Add("A");
list1.Add("B");
list1.Add("C");
list1.Add("D");

// second list
List < string > list2 = new List < string > ();
list2.Add("C");
list2.Add("D");
foreach(string value in list2) {
   Console.WriteLine(value);
}

要取得差異,請使用 IEnumerable 和 Except(),如下所示。第三個列表中顯示了差異- 

IEnumerable < string > list3;
list3 = list1.Except(list2);

以下是完整程式碼- 

示例

 現場演示

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main() {
      List < string > list1 = new List < string > ();
      list1.Add("A");
      list1.Add("B");
      list1.Add("C");
      list1.Add("D");

      Console.WriteLine("First list...");
      foreach(string value in list1) {
         Console.WriteLine(value);
      }

      Console.WriteLine("Second list...");
      List < string > list2 = new List < string > ();

      list2.Add("C");
      list2.Add("D");
      foreach(string value in list2) {
         Console.WriteLine(value);
      }

      Console.WriteLine("Difference in the two lists...");
      IEnumerable < string > list3;
      list3 = list1.Except(list2);
      foreach(string value in list3) {
         Console.WriteLine(value);
      }

   }
}

輸出

First list...
A
B
C
D
Second list...
C
D
Difference in the two lists...
A
B

更新於:2020-06-22

2K+ 瀏覽量

開啟您的職業生涯

完成此課程以獲得認證

開始
廣告
© . All rights reserved.