I’m trying to compare a list of strings compiled together against a master list and print them out to a text file. The problem I’m having is the printable list remains empty. How do I populate the third list? And, is this a proper use of List<>, if not, what should I use?
Edit: Sorry about that, prior to this method running, textInput and textCompare read from two files and are populated with strings 7 characters in length: one pulled from a text file, the other from an excel sheet. I then remove any nulls, and attempt to compare the two lists with listA.intersects(listB). MSDN mentioned it need to be enumerated through for the intersects to work, which is why I put it in a foreach.
void Compare()
{
List<string> matches = new List<string>();
textInput.Sort();
textCompare.Sort();
progressBar.Maximum = textInput.Count;
int increment = 0;
for (int i = textCompare.Count - 1; i >= 0; i--)
{
if (textCompare[i] == null)
{
textCompare.RemoveAt(i);
}
}
foreach (string item in textInput)
{
matches = textInput.Intersect(textCompare).ToList();
increment++;
progressBar.Value = increment;
}
//A break point placed on the foreach reveals matches is empty.
foreach (object match in matches)
{
streamWriter.WriteLine(match);
}
doneLabel.Text = "Done!";
}
From the description in your comment this would do it:
Note that you can remove the
.Where()condition provided you don’t have empty strings in your masterlist “textInput” (very likely there aren’t). Also, if order doesn’t matter remove the.OrderBy(), you end up with this then: