Reputation: 145
I am trying to get the common elementes of two lists. The example is as follows:
var control = "F, H, S, W".Split(',').ToList();
var drives = new List<string> {"C", "D", "E", "F", "H" };
var common = drives.Intersect(control).ToList();
common.ForEach(x =>
{
MessageBox.Show(x);
});
Normally F
and H
should return here, but only F
returns. I don't make any sense.
Upvotes: 0
Views: 49
Reputation: 54
When you split the string "F, H, S, W"
you get the Array [ "F", " H", " S", " W" ]
. Because there are spaces after each comma, they are in the split array aswell. Therefore, if you compare "H"
to " H"
it's false because of the spaces. You can fix this issue by calling the .Trim()
function on each element of the split list to remove all leading and ending spaces.
var control = "F, H, S, W".Split(',').Select(x => x.Trim()).ToList();
var drives = new List<string> { "C", "D", "E", "F", "H" };
var common = drives.Intersect(control).ToList();
common.ForEach(x =>
{
MessageBox.Show(x);
});
Upvotes: -1