[英]C# - Finding the common members of two List<T>s - Lambda Syntax
所以我写了这个简单的控制台应用程序,以帮助我的问题。 在方法的第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());
}
}
你想要Intersect()
:
IEnumerable<int> j = c.Intersect(a);
这是一个基于注释中提到的想法的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;
}
}
}
}
如果你通过lambda语法表示一个真正的LINQ查询,它看起来像这样:
IEnumerable<int> j =
from cItem in c
join aitem in a on cItem equals aItem
select aItem;
lambda表达式是在使用=>运算符时,如:
IEnumerable<int> x = a.Select(y => y > 5);
你使用Union方法实际上是一种非LINQ方式,但我想你的意思是一种没有扩展方法的方法。 对此几乎没有单线。 我昨天使用词典做了类似的事。 你可以这样做:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.