Intersect vs IntersectWith in C#

Shervan360 1,661 Reputation points
2022-10-27T17:19:56.627+00:00

Hello,

I understood how IntersectWith works but How does Interset work in C#?

using System;  
class TestsRethrow  
{  
    static void Main()  
    {  
        string[] Family = { "Harrison", "Joe", "Grace" };  
        string[] Friends = { "Jake", "Mary", "Joe" };  
  
        HashSet<string> duplicate = new(Friends);  
        HashSet<string> duplicateWith = new(Friends);  
  
        duplicate.Intersect(Family); // How it works?  
        duplicateWith.IntersectWith(Family);  
  
        Console.WriteLine($"Intersect {duplicate.Count}");  
  
        foreach (var item in duplicate)  
        {  
            Console.WriteLine(item);  
        }  
        Console.WriteLine("\n");  
        Console.WriteLine($"Intersect With {duplicateWith.Count}");  
        foreach (var item in duplicateWith)  
        {  
            Console.WriteLine(item);  
        }  
    }  
}  
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2022-10-27T17:29:28.93+00:00

    IntersectWith is a mutable operation where Intersect is immutable. This means that IntersectWith modifies duplicateWith whereas Intersect will generate a new IEnumerable containing the duplicates.

    If you change line 12 with this then the value that's returned from Intersect will be set back to the original variable:

       duplicate = duplicate.Intersect(Family).ToHashSet();  
    

    Note that because Intersect returns an IEnumerable rather than a HashSet the .ToHashSet() call at the end will convert it.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-10-27T17:43:32.953+00:00

    It’s pretty simple. Intersect returns a new enumerable, while InterectWith mutates the hash set.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.