In the below code if I iterated over L3 I would expect to have 2 results available. However it only has one result and that result is the objTest with a Id = 9. I thought it should be a result set with two objtest s' Id = 9 and Id = 10.
class Program
{
public class objTest
{
public int Value { get; set; }
public bool On { get; set; }
public int Id { get; set; }
}
class PramComp : EqualityComparer<objTest>
{
public override bool Equals(objTest x, objTest y)
{
return x.Value == y.Value;
}
public override int GetHashCode(objTest obj)
{
return obj.Value.GetHashCode();
}
}
static void Main(string[] args)
{
List<objTest> L1 = new List<objTest>();
L1.Add(new objTest { Value = 1, On = true ,Id =1});
L1.Add(new objTest { Value = 2, On = false ,Id =2});
L1.Add(new objTest { Value = 3, On = false, Id = 3 });
L1.Add(new objTest { Value = 4, On = false ,Id =4});
L1.Add(new objTest { Value = 5, On = false ,Id =5});
List<objTest> L2 = new List<objTest>();
L2.Add(new objTest { Value = 6, On = false ,Id =6});
L2.Add(new objTest { Value = 7, On = false ,Id=7});
L2.Add(new objTest { Value = 8, On = false,Id =8 });
L2.Add(new objTest { Value = 1, On = true,Id =9 });
L2.Add(new objTest { Value = 1, On = true, Id =10 });
var L3 = L2.Intersect(L1, new PramComp());
}
}
So I have made a mistake with my code if I want to return the two results Id=9 and Id=10. Could someone tell me where my mistake is?
Enumerable.Intersect is designed to produce:
the set intersection of two sequences.
A "set" does not allow duplicate values, which means you'll only get one of the two values.
If you want to return both of the ones that match, you could use:
var L3 = L2.Where(item => L1.Any(one => one.Value == item.Value));
This will go through the L2
collection and find all items which have any matching value in L1
, but preserve the duplicates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With