Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,700 questions

57,013 answers

573 users

How to find the intersection of two arrays (values that exist in both arrays) in C#

2 Answers

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

public static class ArrayUtilities
{
    /// <summary>
    /// Finds the unique intersection of two collections (values that exist in both).
    /// Compatible with all Mono runtime versions and standard .NET.
    /// </summary>
    /// <typeparam name="T">The type of elements in the collections.</typeparam>
    /// <param name="first">The first input sequence.</param>
    /// <param name="second">The second input sequence.</param>
    /// <returns>An array containing unique common elements.</returns>
    public static T[] FindArrayIntersection<T>(IEnumerable<T> first, IEnumerable<T> second)
    {
        // Mono-compatible guard clauses
        if (first == null) throw new ArgumentNullException(nameof(first));
        if (second == null) throw new ArgumentNullException(nameof(second));

        // LINQ Intersect uses HashSet internally for linear O(n + m) time complexity
        return first.Intersect(second).ToArray();
    }
}

public class Program
{
    public static void Main()
    {
        // Legacy-safe array initialization (compatible across all Mono compiler targets)
        int[] arr1 = new int[] { 5, 7, 1, 1, 3, 0, 6, 2 };
        int[] arr2 = new int[] { 2, 8, 8, 6, 9, 3, 3, 4, 4 };

        // Execute intersection
        int[] intersection = ArrayUtilities.FindArrayIntersection(arr1, arr2);

        // Print results
        Console.WriteLine("Arr1: [{0}]", string.Join(", ", arr1));
        Console.WriteLine("Arr2: [{0}]", string.Join(", ", arr2));
        Console.WriteLine("Intersection: [{0}]", string.Join(", ", intersection));
        // Output: Intersection: [3, 6, 2]
    }
}


/*
run:

Arr1: [5, 7, 1, 1, 3, 0, 6, 2]
Arr2: [2, 8, 8, 6, 9, 3, 3, 4, 4]
Intersection: [3, 6, 2]

*/

 



answered Sep 28 by avibootz
0 votes
using System;
using System.Collections.Generic;

public static class ArrayUtilities
{
    public static T[] FindArrayIntersectionLowAlloc<T>(T[] first, T[] second)
    {
        if (first == null) throw new ArgumentNullException(nameof(first));
        if (second == null) throw new ArgumentNullException(nameof(second));
    
        // Optimize memory footprint by populating lookup table with the smaller array
        if (first.Length > second.Length) {
            return FindArrayIntersectionLowAlloc(second, first);
        }
    
        // Direct instantiation avoids LINQ iterator class allocations
        HashSet<T> lookup = new HashSet<T>(first);
        List<T> result = new List<T>(first.Length);
    
        for (int i = 0; i < second.Length; i++)
        {
            // HashSet.Remove returns true on match and automatically removes duplicates
            if (lookup.Remove(second[i])) {
                result.Add(second[i]);
            }
        }
    
        return result.ToArray();
    }
    public static void Main()
    {
        // Legacy-safe array initialization (compatible across all Mono compiler targets)
        int[] arr1 = new int[] { 5, 7, 1, 1, 3, 0, 6, 2 };
        int[] arr2 = new int[] { 2, 8, 8, 6, 9, 3, 3, 4, 4 };

        // Execute intersection
        int[] intersection = FindArrayIntersectionLowAlloc(arr1, arr2);

        // Print results
        Console.WriteLine("Arr1: [{0}]", string.Join(", ", arr1));
        Console.WriteLine("Arr2: [{0}]", string.Join(", ", arr2));
        Console.WriteLine("Intersection: [{0}]", string.Join(", ", intersection));
    }
}


/*
run:

Arr1: [5, 7, 1, 1, 3, 0, 6, 2]
Arr2: [2, 8, 8, 6, 9, 3, 3, 4, 4]
Intersection: [2, 6, 3]

*/

 



answered Sep 28 by avibootz
...