Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect not giving expected results

Tags:

c#

.net

linq

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?

like image 281
Paul Stanley Avatar asked Dec 20 '22 23:12

Paul Stanley


1 Answers

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.

like image 180
Reed Copsey Avatar answered Dec 26 '22 20:12

Reed Copsey