In the following code, I expect the result has 2 elements with same values("Item1","Item1") but the result
has 1 element("Item1"):
var list = new List<string>(){"Item1","Item1"};
var emptyList = new List<string>();
// I expect the result of follwing line be {"Item1","Item1"} but is {"Item1"}
var result = list.Except(emptyList);
Seems Except()
method return unique values of the result set, How can I get desired value?
CodePudding user response:
You could use the following:
var result = list.Where(s => !emptyList.Contains(s));
Performance will be worse but whether that matters depends on your dataset.
CodePudding user response:
The definition itself has set.
Produces the set difference of two sequences.
If you read the documentation carefully.
The set difference between two sets is defined as the members of the first set that don't appear in the second set.
This method returns those elements in first that don't appear in second. It doesn't return those elements in second that don't appear in first. Only unique elements are returned.
Workaround is to use list.Where(x => !emptyList.Contains(x))
Also, refer to this question for more clarity.
CodePudding user response:
Just mock the ExceptIterator, replace Add
with Contains
private static IEnumerable<TSource> ExceptOrdinaryIterator<TSource>(
IEnumerable<TSource> first, IEnumerable<TSource> second)
{
var set = new HashSet<TSource>(second);
foreach (TSource element in first)
if (!set.Contains(element))
yield return element;
}