简体   繁体   中英

Compare list<sting> with foreach loop ignoring case c#

I have an application can compare two lsts of data the user inputs. Currently however, if two values are the same but one is upper case the application classes this as not a match.

Now I have used StringComparison.InvariantCultureIgnoreCase before but I am unsure of how to add this within a foreach loop.

My current code is as follows;

List<string> mylistA = new List<string>();
List<string> mylistB = new List<string>();

if (listATextBox.LineCount > 0) 
    for (int i = 1; i <= listATextBox.LineCount; i++) 
        mylistA.Add(listATextBox.GetLineText(i - 1).Replace(Environment.NewLine, "").Trim());

if (listBTextBox.LineCount > 0) 
    for (int i = 1; i <= listBTextBox.LineCount; i++) 
        mylistB.Add(listBTextBox.GetLineText(i - 1).Replace(Environment.NewLine, "").Trim());

foreach (string line in mylistA)
{             
    if (mylistB.Contains(line))
    {
            ResultsToDocument();
    }
}

You can use Enumerable.Contains with this comparer as parameter instead of List.Contains :

foreach (string line in mylistA)
{
    if (mylistB.Contains(line, StringComparer.InvariantCultureIgnoreCase))
    {
        ResultsToDocument();
    }
}

A more efficient approach would be Intersect which also has this overload:

foreach(string line in mylistA.Intersect(mylistB, StringComparer.InvariantCultureIgnoreCase))
     ResultsToDocument(); // does this make sense, not passing the line?

Try this:

foreach (string line in mylistA)
{
    if (mylistB.Any(b => b.Equals(line, StringComparison.OrdinalIgnoreCase)))
    {
        ResultsToDocument();
    }
}

For better performance and readability you can use Intersect

foreach (var element in mylistA.Intersect(mylistB, StringComparer.OrdinalIgnoreCase))
   ResultsToDocument();

If there are duplicates in mylistA that needs to be preserved. Using a hashset for the lookup would be the right way to go and would have the same performance as the intersect solution.

var set = new HashSet<string>(mylistB, StringComparer.OrdinalIgnoreCase)
foreach (string line in mylistA)
{             
    if (set.Contains(line))
    {
         ResultsToDocument();
    }
}

I'd go with:

    foreach (string lineA in mylistA)
    {     
       foreach (string lineB in mylistB)
       {                     
            if (lineB.ToUpper() == lineA.ToUpper())
            {
                  ResultsToDocument();
            }
       }
    }

but there are probably better solutions to achieve the same result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM