2つのコレクションに交差があるかどうかを確認する必要があります。その方法では、LINQの「Join」を使用して2つのコレクションの交差を取得してから、「Any」を使用します。しかし、私はこれを行う他のより「エレガントな」方法があるのだろうか?
4868 次
4 に答える
20
Enumerable.Intersect
おそらくあなたが探しているものです。
MSDNから:
int[] id1 = { 44, 26, 92, 30, 71, 38 };
int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };
IEnumerable<int> both = id1.Intersect(id2);
if(both.Any())...
于 2012-05-16T22:06:52.230 に答える
12
bool intersects = collection1.Intersect(collection2).Any();
これは、コレクションのメンバー(たとえば、プリミティブの場合)の同等性とハッシュコードの「適切な」実装を前提としています。それ以外の場合は、カスタムを渡すことができますIEqualityComparer
。
于 2012-05-16T22:07:03.943 に答える
2
使用する拡張メソッドを次に示します。
public static bool IntersectAny<T>(this IEnumerable<T> first, IEnumerable<T> second, IEqualityComparer<T> comparer = null) {
return first.Intersect(second, comparer).Any();
}
于 2016-09-16T13:50:05.773 に答える
-1
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspxをご覧ください。詳細については、http://www.codeproject.com/Articles/383749/How-をご覧ください。 does-it-work-in-Csharp-Part-3-Csharp-Linq-in-dは非常に役立ちます。
于 2012-05-17T00:24:35.000 に答える