### 检查数组是否是另一个数组的子集

39404 观看

8回复

43153 作者的声誉

``````List<double> t1 = new List<double> { 1, 3, 5 };
List<double> t2 = new List<double> { 1, 5 };
``````

### 回应 (8)

-1

596440 作者的声誉

``````static bool IsSubSet<A>(A[] set, A[] toCheck) {
return set.Length == (toCheck.Intersect(set)).Count();
}
``````

55

439417 作者的声誉

``````HashSet<double> t1 = new HashSet<double>{1,3,5};
HashSet<double> t2 = new HashSet<double>{1,5};

bool isSubset = t2.IsSubsetOf(t1);
``````

241

54671 作者的声誉

``````bool isSubset = !t2.Except(t1).Any();
``````

6

3150 作者的声誉

@ Cameron的解决方案作为扩展方法：

``````public static bool IsSubsetOf<T>(this IEnumerable<T> a, IEnumerable<T> b)
{
return !a.Except(b).Any();
}
``````

``````bool isSubset = t2.IsSubsetOf(t1);
``````

（这与@ Michael博客上发布的内容类似，但不完全相同）

11

1437 作者的声誉

``````CollectionAssert.IsSubsetOf(subset, superset);
``````

``````CollectionAssert.IsSubsetOf(t2, t1);
``````

6

71 作者的声誉

``````bool isSubset = t2.All(elem => t1.Contains(elem));
``````

``````bool isSubset = true;
foreach (var element in t2) {
if (!t1.Contains(element)) {
isSubset = false;
break;
}
}
``````

0

1376 作者的声誉

``````/// <summary>
/// Determines whether a sequence contains the specified elements by using the default equality comparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="source">A sequence in which to locate the values.</param>
/// <param name="values">The values to locate in the sequence.</param>
/// <returns>true if the source sequence contains elements that have the specified values; otherwise, false.</returns>
public static bool ContainsAll<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> values)
{
return !values.Except(source).Any();
}
``````

0

1168 作者的声誉

``````bool isSubset = !(t2.Any(x => !t1.Contains(x)));
``````