2010-02-18 150 views

回答

4

您可以通过.Intersect()模拟这种检查在路口设置了所有必需的元素。我想这是相当低效但又快又脏。

List<T> list = ... 
List<T> shouldBeContained = ... 
bool containsAll = (list.Intersect(shouldBeContained).Count == shouldBeContained.Count) 

或者你可以用.All()来做到这一点。我想这是更有效的和更清洁:

List<T> list = ... 
List<T> shouldBeContained = ... 
bool containsAll = (shouldBeContained.All(x=>list.Contains(x)); 
0

LINQ的具有许多可用于检查一组在另一个值中的存在的操作符。

我会用Intersect

Produces the set intersection of two sequences by using the default equality comparer to compare values.

0

虽然没有什么简单的内置在...你总是可以创建扩展方法,使生活更轻松:

public static bool ContainsAny<T>(this IEnumerable<T> data, 
    IEnumerable<T> intersection) 
{ 
    foreach(T item in intersection) 
     if(data.Contains(item) 
      return true; 
    return false; 
} 

public static bool ContainsAll<T>(this IEnumerable<T> data, 
    IEnumerable<T> intersection) 
{ 
    foreach(T item in intersection) 
     if(!data.Contains(item)) 
      return false; 
    return true; 
}