I've tried the methods here:
- Compare two List<string> and print the duplicates
- Is there any way to compare two lists in C#
- https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/how-to-find-the-set-difference-between-two-lists-linq.
None of the above solved my issue.
I have two lists, List1, and List2. List2 is a .txt file read into a string and then split into a list using commas. List1 is the output of a browser handle split using '-'. So, for example, List1 has the items "Stack Overflow", "Personal", "Microsoft Edge", and List2 has the items "Personal", and "Microsoft Edge". So, there is an overlap between the two lists. I've tried the methods below, with no success.
List<string> duplicates = List2.Intersect(List1).ToList();
if (duplicates.Count > 0)
{
foreach(var dup in duplicates)
{
Console.WriteLine(dup);
}
}
else
{
Console.WriteLine("No");
}
This always will throw a no, even though I thought intersect would find ANY sort of duplicates and give it to the list. To be clear, I am hoping for the outcome "Personal" and "Microsoft Edge". I've also tried
bool match = List1.Contains(TextDoc);
if (match)
{
Console.WriteLine("Match");
}
else
{
Console.WriteLine("no Match");
}
TextDoc is just the txt document read into a string using File.ReadAllText. Neither of these options gives me a match, even though as far as I can tell both of them should given the context of the Lists. Am I missing something super obvious here?
CodePudding user response:
even though I thought intersect would find ANY sort of duplicates and give it to the list
Your thought is correct.
Am I missing something super obvious here?
You are missing to draw the straightforward and simple conclusion: Your assumption that there are some duplicate strings between List1 and List2 is simply incorrect.
Inspect the strings in both lists carefully in the debugger. Do not trust your assumptions about what strings are in the list. You already got the evidence that there are no duplicates in both lists when the Intersect method is being invoked. Verify very carefully what is in both lists at the exact moment the Intersect method is being invoked.
As a side note: Also keep in mind that there are Unicode control characters that are invisible (but inspecting the strings in the debugger should reveal such control characters), and there are different Unicode characters that look similar if not identical (depending on the font used) despite being different characters. And your strings might perhaps feature one or the other, making them look the same but actually containing different character sequences, thus essentially making them unequal strings.