Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Combine Two Lists With Overlapping Data

If I have 2 lists of strings

List<string> history = new List<string>(){ "AA", "BB", "CC", "AA" };
List<string> potentialNew = new List<string>(){ "CC", "AA", "DD", "EE", "FF", "AA"};

I need a way to combine the lists while preventing "overlap" and retaining the same ordering. So, in the example above, there would be a combined list that is:

AA, BB, CC, AA, DD, EE, FF, AA

In other words only DD, EE, FF, and AA are added to the history list.

I've been trying to figure this out for a few days now, and countless searches have yielded no solution. Any help would be greatly appreciated!

like image 211
chutch1122 Avatar asked Mar 13 '23 23:03

chutch1122


1 Answers

This will give you the expected output for the set of given input as you mentioned in the question:

 List<string> history = new List<string>() { "AA", "BB", "CC", "AA" };
 List<string> potentialNew = new List<string>() { "CC", "AA", "DD", "EE", "FF" };
 var result = history.Concat(potentialNew.Where(x => !history.Contains(x)).ToList());

The .Concat() method allows you to Concatenates two list. we are extracting particular items from the potentialNew that are not present in the first List and concat them with the first list.

Update : As per our discussion I Came in a conclusion that you are looking for something like the following:

string lastItem = history.Last();
   int lastIndexToCheck=history.Count-2,i=0;
   for (; i < potentialNew.Count - 1; i++)
       {
          if (potentialNew[i] == lastItem && potentialNew[i - 1] == history[lastIndexToCheck])
              {
                 break;
              }
       }
       history.AddRange(potentialNew.Skip(i+1).ToList());  

Now history will contains the required set of elements.

like image 169
sujith karivelil Avatar answered Mar 21 '23 03:03

sujith karivelil