Search code examples
c#if-statementwhile-loopcontains

Return true per item if list1 contains part of any string from list2


If a string(or part of a string) from list1 is the same as a string in list2 the string needs to be added to a listbox.

I now have:

            int g = 0;

            while (g < musthaves.Count())
            {
                if (list1.Contains(list2[g].ToString()))
                {
                    listBox14.Items.Add("Found: " + list2[g].ToString());
                }
                else
                {
                    listBox14.Items.Add("Not found: " + list2[g].ToString());
                }
                g++;
            }

The list are:

list1:
testcase scan document
testcase upload document
testcase delete document

list2:
upload document
scan document
indicate inconsistency


So the listbox should contain:

Found: upload document
Found: scan document
Not found: indicate inconsistency

But my results are Not found for every string.

Any help is appreciated.


Solution

  • You are checking only that full string is one of the item in the another list, but your requirement is

    If a string (or part of a string) from list1 is the same as a string in list2

    So you need to check every phrase in list2 if phrase contains one of the expected phrases from the list1 (uhh, I would suggest to use more descriptive names for variables - will simplify conversations :))

    foreach (var requiredPhrase in list1)
    {
        if (list2.Any(phrase => phrase.Contains(requiredPhrase))
        {
            // Found
        }
        else
        {
            // Not found
        }
    }