Check whether an array is a subset of another

2018-12-31 18:11发布

Any idea on how to check whether that list is a subset of another?

Specifically, I have

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

How to check that t2 is a subset of t1, using LINQ?

8条回答
查无此人
2楼-- · 2018-12-31 18:25

Try this

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

The idea here is that Intersect will only return the values that are in both Arrays. At this point if the length of the resulting set is the same as the original set, then all elements in "set" are also in "check" and therefore "set" is a subset of "toCheck"

Note: My solution does not work if "set" has duplicates. I'm not changing it because I don't want to steal other people's votes.

Hint: I voted for Cameron's answer.

查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 18:33

If you are unit-testing you can also utilize the CollectionAssert.IsSubsetOf method :

CollectionAssert.IsSubsetOf(subset, superset);

In the above case this would mean:

CollectionAssert.IsSubsetOf(t2, t1);
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 18:34

Building on the answers from @Cameron and @Neil I wrote an extension method that uses the same terminology as the Enumerable class.

/// <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();
}
查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 18:38
bool isSubset = !t2.Except(t1).Any();
查看更多
大哥的爱人
6楼-- · 2018-12-31 18:44

@Cameron's solution as an extension method:

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

Usage:

bool isSubset = t2.IsSubsetOf(t1);

(This is similar, but not quite the same as the one posted on @Michael's blog)

查看更多
与风俱净
7楼-- · 2018-12-31 18:48

Here we check that if there is any element present in the child list(i.e t2) which is not contained by the parent list(i.e t1).If none such exists then the list is subset of the other

eg:

bool isSubset = !(t2.Any(x => !t1.Contains(x)));
查看更多
登录 后发表回答