Search code examples
c#liststring-comparisonpartial-matches

Compare 2 lists for partial match


C# Folks! I have 2 List that I want to compare.

Example:

List<string> ONE contains:
A
B
C

List<string> TWO contains:
B
C

I know I can achieve the results of ONE if I do:

ONE.Except(TWO);

Results: A


How can I do the same if my Lists contain a file extension for each Element?


List<string> ONE contains:
A.pdf
B.pdf
C.pdf

List<string> TWO contains: (will always have .txt extension)
B.txt
C.txt

Results should = A.pdf

I realized that I need to display the full filename (A.pdf) in a report at the end, so I cannot strip the extension, like I originally did.

Thanks for the help!

EDIT: This is how I went about it, but I am not sure if this is the "best" or "most performant" way to actually solve it, but it does seem to work...

foreach (string s in ONE)
{
     //since I know TWO will always be .txt
     string temp = Path.GetFileNameWithoutExtension(s) + ".txt";

     if (TWO.Contains(temp))
     {
          // yes it exists, do something
     }
     else
     {
          // no it does not exist, do something
     }
}

Solution

  • This a very straightforward and a easy code , but if your requirement has more file extension

        List<string> lstA = new List<string>() { "A.pdf", "B.pdf", "C.pdf" };
    
            List<string> lstB = new List<string>() { "B.txt", "C.txt" };
    
            foreach (var item in lstA)
            {
                if (lstB.Contains(item.Replace(".pdf",".txt"))==false)
                {
                    Console.WriteLine(item);
                }
            }