Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 137221
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T07:04:19+00:00 2026-05-11T07:04:19+00:00

I’m having a problem with my work that hopefully reduces to the following: I

  • 0

I’m having a problem with my work that hopefully reduces to the following: I have two List<int>s, and I want to see if any of the ints in ListA are equal to any int in ListB. (They can be arrays if that makes life easier, but I think List<> has some built-in magic that might help.) And I’m sure this is a LINQ-friendly problem, but I’m working in 2.0 here.

My solution so far has been to foreach through ListA, and then foreach through ListB,

foreach (int a in ListA) {     foreach (int b in ListB)     {         if (a == b)         {             return true;         }     } } 

which was actually pretty slick when they were each three items long, but now they’re 200 long and they frequently don’t match, so we get the worst-case of N^2 comparisons. Even 40,000 comparisons go by pretty fast, but I think I might be missing something, since N^2 seems pretty naive for this particular problem.

Thanks!

  • 1 1 Answer
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T07:04:20+00:00Added an answer on May 11, 2026 at 7:04 am

    With LINQ, this is trivial, as you can call the Intersect extension method on the Enumerable class to give you the set intersection of the two arrays:

    var intersection = ListA.Intersect(ListB); 

    However, this is the set intersection, meaning if ListA and ListB don’t have unique values in it, you won’t get any copies. In other words if you have the following:

    var ListA = new [] { 0, 0, 1, 2, 3 }; var ListB = new [] { 0, 0, 0, 2 }; 

    Then ListA.Intersect(ListB) produces:

    { 0, 2 } 

    If you’re expecting:

    { 0, 0, 2 } 

    Then you’re going to have to maintain a count of the items yourself and yield/decrement as you scan the two lists.

    First, you’d want to collect a Dictionary<TKey, int> with the lists of the individual items:

    var countsOfA = ListA.GroupBy(i => i).ToDictionary(g => g.Key, g => g.Count()); 

    From there, you can scan ListB and place that in a list when you come across an item in countsOfA:

    // The items that match. IList<int> matched = new List<int>();  // Scan  foreach (int b in ListB) {     // The count.     int count;      // If the item is found in a.     if (countsOfA.TryGetValue(b, out count))     {         // This is positive.         Debug.Assert(count > 0);          // Add the item to the list.         matched.Add(b);          // Decrement the count.  If         // 0, remove.         if (--count == 0) countsOfA.Remove(b);     } } 

    You can wrap this up in an extension method that defers execution like so:

    public static IEnumerable<T> MultisetIntersect(this IEnumerable<T> first,     IEnumerable<T> second) {     // Call the overload with the default comparer.     return first.MultisetIntersect(second, EqualityComparer<T>.Default); }  public static IEnumerable<T> MultisetIntersect(this IEnumerable<T> first,     IEnumerable<T> second, IEqualityComparer<T> comparer) {     // Validate parameters.  Do this separately so check     // is performed immediately, and not when execution     // takes place.     if (first == null) throw new ArgumentNullException('first');     if (second == null) throw new ArgumentNullException('second');     if (comparer == null) throw new ArgumentNullException('comparer');      // Defer execution on the internal     // instance.     return first.MultisetIntersectImplementation(second, comparer); }  private static IEnumerable<T> MultisetIntersectImplementation(     this IEnumerable<T> first, IEnumerable<T> second,      IEqualityComparer<T> comparer) {     // Validate parameters.     Debug.Assert(first != null);     Debug.Assert(second != null);     Debug.Assert(comparer != null);      // Get the dictionary of the first.     IDictionary<T, long> counts = first.GroupBy(t => t, comparer).         ToDictionary(g => g.Key, g.LongCount(), comparer);      // Scan      foreach (T t in second)     {         // The count.         long count;          // If the item is found in a.         if (counts.TryGetValue(t, out count))         {             // This is positive.             Debug.Assert(count > 0);              // Yield the item.             yield return t;              // Decrement the count.  If             // 0, remove.             if (--count == 0) counts.Remove(t);         }     } } 

    Note that both of these approaches are (and I apologize if I’m butchering Big-O notation here) O(N + M) where N is the number of items in the first array, and M is the number of items in the second array. You have to scan each list only once, and it’s assumed that getting the hash codes and performing lookups on the hash codes is an O(1) (constant) operation.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a French site that I want to parse, but am running into
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a small JavaScript validation script that validates inputs based on Regex. I
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have been unable to fix a problem with Java Unicode and encoding. The
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.