Diego Slinger
Diego Slinger

Reputation: 149

Two collections intersection

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();

Upvotes: 3

Views: 110

Answers (3)

Salah Akbari
Salah Akbari

Reputation: 39956

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;

Upvotes: 2

Sonikas
Sonikas

Reputation: 131

Intersect return unique matching elements in both lists

Upvotes: 2

Link
Link

Reputation: 1711

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.

Upvotes: 4

Related Questions