Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Finding the common members of two List<T>s - Lambda Syntax

So I wrote this simple console app to aid in my question asking. What is the proper way to use a lambda expression on line 3 of the method to get the common members. Tried a Join() but couldn't figure out the correct syntax. As follow up... is there a non-LINQ way to do this in one line that I missed?

class Program
{
    static void Main(string[] args)
    {
        List<int> c = new List<int>() { 1, 2, 3 };
        List<int> a = new List<int>() { 5, 3, 2, 4 };
        IEnumerable<int> j = c.Union<int>(a);
        // just show me the Count
        Console.Write(j.ToList<int>().Count.ToString());

    }
}
like image 621
BuddyJoe Avatar asked Nov 30 '22 06:11

BuddyJoe


1 Answers

You want Intersect():

IEnumerable<int> j = c.Intersect(a);

Here's an OrderedIntersect() example based on the ideas mentioned in the comments. If you know your sequences are ordered it should run faster — O(n) rather than whatever .Intersect() normally is (don't remember off the top of my head). But if you don't know they are ordered, it likely won't return correct results at all:

public static IEnumerable<T> OrderedIntersect<T>(this IEnumerable<T> source, IEnumerable<T> other) where T : IComparable
{
    using (var xe = source.GetEnumerator())
    using (var ye = other.GetEnumerator())
    {
        while (xe.MoveNext())
        {
           while (ye.MoveNext() && ye.Current.CompareTo(xe.Current) < 0 )
           {
              // do nothing - all we care here is that we advanced the y enumerator
           }
           if (ye.Current.Equals(xe.Current))
              yield return xe.Current;
           else
           {  // y is now > x, so get x caught up again
              while (xe.MoveNext() && xe.Current.CompareTo(ye.Current) < 0 )
              { } // again: just advance, do do anything

              if (xe.Current.Equals(ye.Current)) yield return xe.Current;
           }

        }
    }
}
like image 80
Joel Coehoorn Avatar answered Dec 05 '22 11:12

Joel Coehoorn