Collection Intersection Example

.NET has the ability to compare two or more collection types to see what elements they have in common. The Intersect and IntersectWith methods. In this example I’ll be using these two methods along with the default string comparer and a custom string comparer.

IntersectionSolution IntersectionProgram

 

Program.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySets
{
    class Program
    {
        /// <summary>
        /// This program demonstrates intersections between two collections.
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            executeDefaultHashSetExample();
            executeLinqHashSet();
            excecuteComparerHashSet();
            executeCustomComparer();

            Console.ReadLine();
        }

        // Private methods
        //
        // Method that executes various tasks for a hash set without any kind of comparer.
        private static void executeDefaultHashSetExample()
        {
            Console.WriteLine("----Executing Intersection Example Without Any String Comparer----");

            // Creating a list first for this demonstration.    
            List<string> listCities = new List<string>()
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Rome"
            };

            // Creating hash set with the same cities and add methods.
            HashSet<string> hashSetCities = new HashSet<string>
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Manchester"
            };

            // Using the IntersectWith method to see what the hash set collection and string list have in common.
            // Then displaying the common results.
            // Take note that this method modifies the hash set collection in line. Meaning I don't have to 
            // create a variable to store the new data.
            hashSetCities.IntersectWith(listCities);
            foreach (var item in hashSetCities)
                Console.WriteLine(item);

            Console.WriteLine();
        }

        // Method that executes various tasks for the hash set using a LINQ method.
        private static void executeLinqHashSet()
        {
            Console.WriteLine("----Executing Intersection Example With A LINQ Method----");

            // Creating a list first for this demonstration.    
            List<string> listCities = new List<string>()
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Rome"
            };

            // Creating hash set with the same cities. Some of the same names are in the List collection.
            HashSet<string> hashSetCities = new HashSet<string>
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Manchester"
            };

            // Using the IntersectWith method to see what the hash set collection and string list have in common.
            // Then displaying the common results.
            // Take note that a variable had to be created and the collection elements added to it.
            var newCities = hashSetCities.Intersect(listCities);
            foreach (var item in newCities)
                Console.WriteLine(item);

            Console.WriteLine();
        }

        // Method that executes tasks for a hash set using the .NET comparer.
        private static void excecuteComparerHashSet()
        {
            Console.WriteLine("----Executing Intersection Example With The .NET String Comparer----");

            // Creating a list first for this demonstration.    
            List<string> listCities = new List<string>()
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Rome"
            };

            // Creating hash set with the same cities and add methods.
            HashSet<string> hashSetCities = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Manchester"
            };

            // Using the IntersectWith method to see what the hash set collection and string list have in common.
            // Then displaying the common results.
            // Take note that this method modifies the hash set collection in line. Meaning I don't have to 
            // create a variable to store the new data.
            hashSetCities.IntersectWith(listCities);

            // Testing the string comparer by trying to add items. Note which city gets added and which
            // one doesn't.
            Console.WriteLine("Add New York? {0}", hashSetCities.Add("New York"));
            Console.WriteLine("Add Manchester? {0}", hashSetCities.Add("Manchester"));

            foreach (var item in hashSetCities)
                Console.WriteLine(item);

            Console.WriteLine();
        }

        // Method that executes tasks for a hash set using a custom comparer.
        private static void executeCustomComparer()
        {
            Console.WriteLine("----Executing Intersection Example With A Custom String Comparer----");

            // Creating a list first for this demonstration.    
            List<string> listCities = new List<string>()
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Rome"
            };

            // Creating hash set with the same cities. Some of the same names are in the List collection.
            HashSet<string> hashSetCities = new HashSet<string>(new MyEqualityComparer())
            {
                "New York",
                "Paris",
                "Los Angeles",
                "London",
                "Manchester"
            };

            // Using the IntersectWith method to see what the hash set collection and string list have in common.
            // Then displaying the common results.
            // Take note that a variable had to be created and the collection elements added to it.
            var newCities= hashSetCities.Intersect(hashSetCities);
            foreach (var item in newCities)
                Console.WriteLine(item);

            Console.WriteLine();
        }
    }
}

First off you will notice that in the example I’m making calls to a custom string comparer. This is the same one as the last example used. The code hasn’t changed for it because I’ve chosen to still use Hashsets with this example. You can use the Intersect and IntersectWith on any collection type. So keep that in mind.

With these methods along with the string comparers you can perform comparisons between collections to see what elements are the same. Take note that where I’m calling the Intersect and IntersectWith methods I’m doing it with a variable declaration. I’m modifying the collection inline when calling the intersect methods. You can still declare a variable depending on your needs.

I’m also doing a couple other things. Such as adding elements to a collection that an intersect method has run on. Even trying to add an element with the same name thru the different string comparer implementations.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s