C# program to find additional values in two lists

ProgrammingServer Side ProgrammingCsharp

Firstly, set two lists in C#.

List One

List <string> list1 = new List <string> ();
list1.Add("P");
list1.Add("Q");
list1.Add("R");
list1.Add("S");
list1.Add("T");
list1.Add("U");
list1.Add("V");
list1.Add("W");

List Two

List <string> list2 = new List <string> ();
list2.Add("T");
list2.Add("U");
list2.Add("V");
list2.Add("W");

Now, to get the different values in both the lists, use the Except method. It returns the values in the first list which is not present in the second list.

Example

 Live Demo

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");
      list1.Add("S");
      list1.Add("T");
      list1.Add("U");
      list1.Add("V");
      list1.Add("W");
      Console.WriteLine("First list...");

      foreach(string value in list1) {
         Console.WriteLine(value);
      }
      Console.WriteLine("Second list...");
      List <string> list2 = new List <string> ();
      list2.Add("T");
      list2.Add("U");
      list2.Add("V");
      list2.Add("W");

      foreach(string value in list2) {
         Console.WriteLine(value);
      }
      Console.WriteLine("Remaining values...");
      IEnumerable <string> list3;
      list3 = list1.Except(list2);

      foreach(string value in list3) {
         Console.WriteLine(value);
      }
   }
}

Output

First list...
P
Q
R
S
T
U
V
W
Second list...
T
U
V
W
Remaining values...
P
Q
R
S
raja
Published on 11-Sep-2018 11:26:44
Advertisements