Bud*_*Joe 4 .net c# linq lambda list
所以我写了这个简单的控制台应用程序,以帮助我的问题.在方法的第3行使用lambda表达式来获取公共成员的正确方法是什么.尝试了Join()但无法弄清楚正确的语法.作为后续行动......有没有一种非LINQ方式在我错过的一行中做到这一点?
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());
}
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*orn 20
你想要Intersect():
IEnumerable<int> j = c.Intersect(a);
Run Code Online (Sandbox Code Playgroud)
以下是OrderedIntersect()基于评论中提到的想法的示例.如果你知道你的序列是有序的,它应该运行得更快 - O(n)而不是.Intersect()通常的(不记得我的头顶).但如果你不知道他们是订购的,它可能根本不会返回正确的结果:
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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)