Search code examples
c#listexcept

Removing Found Items from a Master List<T>


Okay, So I have two lists, MasterTagList and FoundTagList. The master list is set before hand with what tags should be found. The found list is made up of the tags that the reader actually finds. What I'm trying to do is determine the items in the MasterTagList that were not anywhere in the found tag list, meaning they are completely absent.

I have tried to use the Except() method, but for some reason, if the items are not in the exact order, then it says that all of the items are still missing.

I also tried code that looked something like this:

List<string> missing = new List<string>();
foreach (string T in MasterTagList)
{
    if (!FoundTagList.Contains(T))
    {
        missing.Add(T);
    }
}

I would think that the new list, missing, should show my all of the items that are in MasterTagList, but not in the FoundTagList, regardless of order. I am not an expert in C# by any manner, so I might be miss using something.

I just want to know if there is a way I can modify this code to get it to work, or if there is any other way of going about finding the missing elements, regardless of order.

Thanks in advance!

EDIT: Like I said, I have tried every other option I have seen suggested on here. My Except() instance looked something like this:

List<string> missing = MasterTagList.Except(FoundTagList).ToList;

Yet still, when I run the program, the missing list is always identical to the MasterTagList, although FoundTagList and MasterTagList both contain identical elements, just in different orders.

SOLVED: It turns out that something must have been wrong with the way I was adding things to the lists originally; therefore, the elements in each list were not necessarily identical. I went back and modified how I was adding things to the list and now my program is working perfectly. Thank-you to all of you who had suggestions!


Solution

  • It can be pretty straightforward with the Except method

    List<string> missing = MasterTagList.Except(FoundTagList).ToList();
    

    EDIT

    This can be verified with the following. Note that the order of the lists do not matter. It will still produce an empty list (none missing).

    List<string> Master = new List<string>()
        { "a", "b", "c", "d", "e", "f", "g", "h" };
    
    List<string> Found = new List<string>() 
        { "g", "d", "e", "h", "a", "b", "c", "f" };
    
    List<string> missing = Master.Except(Found).ToList();
    
    Console.WriteLine(missing.Count); //Prints 0