C# – 查找两个List s – Lambda语法的公共成员

所以我写了这个简单的控制台应用程序,以帮助我的问题。 在方法的第3行使用lambda表达式来获取公共成员的正确方法是什么。 尝试了Join()但无法弄清楚正确的语法。 作为后续行动……有没有一种非LINQ方式在我错过的一行中做到这一点?

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

你想要Intersect()

 IEnumerable j = c.Intersect(a); 

这是一个基于评论中提到的想法的OrderedIntersect()示例。 如果你知道你的序列是有序的,它应该运行得更快 – O(n)而不是任何.Intersect()通常是(不记得我的头顶)。 但如果你不知道他们是订购的,它可能根本不会返回正确的结果:

 public static IEnumerable OrderedIntersect(this IEnumerable source, IEnumerable 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; } } } } 

如果你使用lambda语法意味着一个真正的LINQ查询,它看起来像这样:

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

lambda表达式是在使用=>运算符时,如:

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

你使用Union方法实际上是一种非LINQ方式,但我想你的意思是一种没有扩展方法的方法。 对此几乎没有单线。 我昨天使用词典做了类似的事。 你可以这样做:

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