How to compare two lists and add the difference to a third list in C#?

WBOY
Release: 2023-09-17 19:21:03
forward
685 people have browsed it

如何在 C# 中比较两个列表并将差异添加到第三个列表?

First, set up two lists -

list one

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

list two

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

find between the two lists and display the difference elements -

IEnumerable < string > list3;
list3 = list1.Except(list2);
foreach(string value in list3) {
   Console.WriteLine(value);
}
Copy after login

Here is a complete example of comparing two lists-

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("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);
      }
   }
}
Copy after login

The above is the detailed content of How to compare two lists and add the difference to a third list in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!