Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two lists and generate new one with matching results C#

Tags:

c#

list

Hi people I'm a beginner computer engineer and I have a little problem.

I'm trying to compare two lists (list A and list B) with different sizes and generate a new one (list C) with the same size as list A containing the matching results of the two lists in C#. Here - let me explain with an exemple.

For instance there are these two lists:

list A: "1", "2", "3", "4", "5", "6"
list B: "1", "4", "5"

And I want this result:

list C: "1", "null", "null", "4", "5", "null"

So far, I've tried this code:

List<string> C = new List<string>();

// nA is the length of list A & nB is the length of list B 
for (int x = 0; x < nA; x++)
{
     for (int y = 0; y < nB; y++)
     {
         if (listA[x] == listB[y])
         {
            listC.Add(lista[x]);
         }
         else
            listC.Add(null);
     }
}

The code I used doesn't do what it's supposed to. What am I doing wrong? Is there another way to do what I need? I need some help and I hope that the solution of my problem can help someone else as well. I hope I've made myself clear and hope you guys can help me with my problem. I'll be very thankful for your help.

Many thanks for the answers :)

like image 350
Mr. Engineer Avatar asked Feb 03 '26 05:02

Mr. Engineer


1 Answers

You can use this LINQ query:

List<string> listC = listA
    .Select(str => listB.Contains(str) ? str : "null")
    .ToList();

I would use it since it's much more readable and maintainable.

like image 115
Tim Schmelter Avatar answered Feb 05 '26 18:02

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!