Reputation: 63
I have two list namely, list1 and list2
Suppose if my list1 has the following elements,
"first", "second","third"
and my list2 has the following elements,
"element first is present here"
"elements are present in second"
So in this case, the string "first" and "second" are present in the list2.(but not exactly the same as in variablelist).
So in this case, how can I except "first" and "second" and show my result as, only "third" element is not present in the list2?
I am using the following code
var inOnlyVariableList = list1.Except(list2).ToList();
Thanks in Advance
Upvotes: 0
Views: 1708
Reputation: 460138
You can't use a set based approach(like Except
) if you search substrings. So it's not as efficient but still readable:
var inOnlyVariableList = list1.Where(s => !list2.Any(s2 => s2.Contains(s))).ToList();
String.Contains
looks if the given string is contained in the larger string.
If you want to support case insensitive comparison you can use:
var inOnlyVariableList = list1
.Where(s => list2.All(s2 => s2.IndexOf(s, StringComparison.InvariantCultureIgnoreCase) == -1))
.ToList();
Upvotes: 5