C # - Finding common elements from two List <T> s - Lambda Syntax

So, I wrote this simple console application to help with the question of my question. What is the correct way to use a lambda expression in line 3 of a method to get common members. I tried connection () but could not determine the correct syntax. As a follow-up ... is there a non-LINQ-related way to do this on the same line I skipped?

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()); } } 
+4
source share
2 answers

Do you want Intersect() :

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

Here's an example of OrderedIntersect() based on the ideas mentioned in the comments. If you know that your sequences are ordered, it should work faster - O(n) , and not something .Intersect() usually (don’t remember from the head). But if you do not know that they are ordered, most likely they will not return the correct results:

 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; } } } } 
+20
source

If you mean the real LINQ query by lambda syntax, it looks like this:

 IEnumerable<int> j = from cItem in c join aitem in a on cItem equals aItem select aItem; 

A lambda expression is when you use the => operator, for example:

 IEnumerable<int> x = a.Select(y => y > 5); 

What you have with the Union method is really a way other than LINQ, but I assume that you mean a way to do this without extension methods. For this, there is hardly a single liner. Yesterday I did something similar using a dictionary. You can do the following:

 Dictaionary<int, bool> match = new Dictaionary<int, bool>(); foreach (int i in c) match.Add(i, false); foreach (int i in a) { if (match.ContainsKey(i)) { match[i] = true; } } List<int> result = new List<int>(); foreach (KeyValuePair<int,bool> pair in match) { if (pair.Value) result.Add(pair.Key); } 
+2
source

All Articles