Mr. Engineer
Mr. Engineer

Reputation: 33

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

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 :)

Upvotes: 3

Views: 177

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460048

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.

Upvotes: 7

Iftah
Iftah

Reputation: 9572

You are adding null for each unequal value in B.

Try this:

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++)
{
     boolean found = false;
     for (int y = 0; y < nB; y++)
     {
         if (listA[x] == listB[y])
         {
            listC.Add(lista[x]);
            found = true;
            break;
         }
     }
     if (!found)
        listC.Add(null);

}

Upvotes: 2

Sayse
Sayse

Reputation: 43300

I don't think you need the inner loop, you just need to keep a note of the current index you are looking at in list b, and increment it if listA contains that item. Note this may require extra error handling

int currentIdx = 0;

for (int x = 0; x < nA; x++)
{
     if (listA[x] == listB[currentIdx])
     {
        listC.Add(lista[x]);
        currentIdx++;
     }
     else
        listC.Add(null);     
}

Upvotes: 0

usr
usr

Reputation: 171178

Get away from manual looping. I'd use a query. The idea would be to join the item in the second list to the first. If the join fails, we'll emit null.

var results =
 from a in listA
 join b in listB on a equals b into j
 let b = j.SingleOrDefault()
 select b == null ? "null" : a;

Upvotes: 0

Related Questions