所以我写了这个简单的控制台应用程序在我的问题问到帮助。 什么是使用的方法的第3行lambda表达式来获得对普通会员的正确方法。 尝试了加入(),但无法找出正确的语法。 作为跟进...有一个非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);
你必须与欧盟法真正是做这件事的非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);
}