你能使用linq来查看两个IEnumerables数据是否包含任何公共条目?

时间:2011-03-07 16:53:56

标签: c# .net linq ienumerable

IEnumerable<fishbiscuits> a = GetFishBiscuits(0);
IEnumerable<fishbiscuits> b = GetFishBiscuits(1);

if ([any of the results in either list match])
{
 // Do something ie
 Console.WriteLine("I see both a and b love at least one of the same type of fish biscuit!");
}

您是否可以使用linq查看两个IEnumerables数据是否包含任何公共条目?

2 个答案:

答案 0 :(得分:9)

是的,您可以使用IntersectAny执行此操作:

bool anyCommonEntries = a.Intersect(b).Any();

答案 1 :(得分:1)

public void Linq50()
{
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
    int[] numbersB = { 1, 3, 5, 7, 8 };

    var commonNumbers = numbersA.Intersect(numbersB);

    Console.WriteLine("Common numbers shared by both arrays:");
    foreach (var n in commonNumbers)
    {
        Console.WriteLine(n);
    }
}

来自101 Linq样本 - Intersect

相交

Msdn documentation

Extension Methods Roundup: Intersect, Union, AsNullable and GroupEvery