Compare two lists and create a new one with corresponding C # results

Hi I am a beginner software engineer and I have a little problem.

I am 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 example.

For example, there are 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 have 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 am using does not do what it was supposed to do. What am I doing wrong? Is there any other way to do what I need? I need help and I hope the solution to my problem can help another too. I hope I made it clear that you guys can help me with my problem. I will be very grateful for your help.

Thanks a lot for the answers :)

+3


source to share


4 answers


You can use this LINQ query:

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

      



I would use it as it is more readable and maintainable.

+7


source


You add null

for every unequal value in B.

Try the following:



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

}

      

+2


source


Step away from the manual loop. I would use a query. The idea would be to join the item in the second list to the first. If the connection fails, we will exit 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;

      

0


source


I don't think you need an inner loop, you just need to keep the current index you are looking at in list b and increment it if listA contains that element. Please note that this may require additional 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);     
}

      

0


source







All Articles