I am trying to intersect two collections. I've got two lists listed below in a code snippet.
This is my output:
Intersection
1
Why is only one value found? Is it the expected behavior or I am doing something wrong?
I expect my output looks like this:
Intersection
1
1
1
1
My code:
// Collection initialization
List<int> list1 = new List<int> { 1,1,1,1 };
List<int> list2 = new List<int> { 1,1,1,1,1,1,1,1,1,1,1 };
foreach (int q in list1)
Console.WriteLine("list1: " + q);
Console.WriteLine("------------------");
foreach (int q in list2)
Console.WriteLine("list2: " + q);
Console.WriteLine("------------------");
Console.WriteLine("Intersection");
IEnumerable<int> both = list1.Intersect(list2);
foreach (int a in both)
Console.WriteLine(a);
Console.ReadLine();
Console.Clear();
As you can read in the description of Enumerable.Intersect:
The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.
In a set you only have distinct objects. So putting four 1s in a set is the same like putting it in only 1 time. Thats why you get only one entry.
LINQ makes your work more easier. Use Contains method like this:
List<int> resultList = list1.Where(c => list2.Contains(c)).ToList();
Just don't forget to add LINQ to your using directives first:
using System.Linq;
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