list2=newList();list2.Add("C");list2.Add(&quo"/> list2=newList();list2.Add("C");list2.Add(&quo">

Home >Backend Development >C#.Net Tutorial >How to compare two lists for equality in C#?

How to compare two lists for equality in C#?

WBOY
WBOYforward
2023-08-26 19:37:081787browse

如何在 C# 中比较两个列表是否相等?

Set up two lists -

list one

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

list two

List < string > list2 = new List < string > ();
list2.Add("C");
list2.Add("D");

Now if the following returns different elements, it means that the lists are not equal -

Example

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

public class Demo {
   public static void Main() {
      List < string > list1 = new List < string > ();
      list1.Add("P");
      list1.Add("Q");
      list1.Add("R");

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

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

      list2.Add("P");
      list2.Add("R");
      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);
      }
   }
}

The above is the detailed content of How to compare two lists for equality in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete