Intersection does not produce the expected results.

In the code below, if I were to repeat L3, I was expecting you to have 2 results. However, it has only one result, and the result is objTest with Id = 9. I thought it should be a result set with two objects 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 made a mistake with my code if I want to return two results Id = 9 and Id = 10. Can someone tell me where my error is?

+4
source share
3 answers

Enumerable.Intersect is designed to create:

the set of intersections of two sequences.

"set" does not allow duplicate values, which means that you get only one of two values.

, , :

var L3 = L2.Where(item => L1.Any(one => one.Value == item.Value));

L2 , L1, .

+8

, Reed Copsey , . . join dictioanry , :

var l3 = from e2 in L2
         join e1 in L1 on e1.Value equals e2.Value
         into grp
         where grp.Any()
         select e2;
+3

Value, id 9 id 10 . , .

0

All Articles