c# 判断是否为数组_c# - 检查数组是否是另一个数组的子集

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

有关如何检查该列表是否是另一个列表的任何想法?

具体来说,我有

List t1 = new List { 1, 3, 5 };

List t2 = new List { 1, 5 };

如何使用LINQ检查t2是否为t1的子集?

Graviton asked 2019-06-08T10:23:02Z

8个解决方案

233 votes

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

Cameron MacFarland answered 2019-06-08T10:23:09Z

52 votes

如果使用集合,请使用HashSet而不是List。 然后你可以简单地使用IsSubsetOf()

HashSet t1 = new HashSet{1,3,5};

HashSet t2 = new HashSet{1,5};

bool isSubset = t2.IsSubsetOf(t1);

对不起,它不使用LINQ。:-(

如果你需要使用列表,那么@Jared的解决方案可以解决你需要删除任何存在的重复元素的问题。

tvanfosson answered 2019-06-08T10:23:48Z

8 votes

如果您是单元测试,您还可以使用CollectionAssert.IsSubsetOf方法:

CollectionAssert.IsSubsetOf(subset, superset);

在上述情况下,这意味着:

CollectionAssert.IsSubsetOf(t2, t1);

Géza answered 2019-06-08T10:24:19Z

6 votes

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

public static bool IsSubsetOf(this IEnumerable a, IEnumerable b)

{

return !a.Except(b).Any();

}

用法:

bool isSubset = t2.IsSubsetOf(t1);

(这与@ Michael博客上发布的内容类似,但不完全相同)

Neil answered 2019-06-08T10:24:52Z

4 votes

这是一个比这里发布的其他解决方案更有效的解决方案,尤其是顶级解决方案:

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

如果你能在t2中找到一个不在t1中的单个元素,那么你知道t2不是t1的子集。 与使用.Except或.Intersect的解决方案不同,这种方法的优点是它可以在所有就地完成,而无需分配额外的空间。 此外,该解决方案能够在找到违反子集条件的单个元素时立即中断,而其他元素继续搜索。 下面是解决方案的最佳长形式,在我的测试中仅比上述速记解决方案略快。

bool isSubset = true;

foreach (var element in t2) {

if (!t1.Contains(element)) {

isSubset = false;

break;

}

}

我对所有解决方案进行了一些基本的性能分析,结果非常激烈。 这两个解决方案比.Except()和.Intersect()解决方案快约100倍,并且不使用额外的内存。

user2325458 answered 2019-06-08T10:25:33Z

0 votes

试试这个

static bool IsSubSet(A[] set, A[] toCheck) {

return set.Length == (toCheck.Intersect(set)).Count();

}

这里的想法是Intersect只返回两个数组中的值。 此时,如果结果集的长度与原始集相同,则“set”中的所有元素也处于“check”状态,因此“set”是“toCheck”的子集

注意:如果“set”具有重复项,则我的解决方案不起作用。 我不是在改变它,因为我不想偷别人的票。

提示:我投票支持Cameron的答案。

JaredPar answered 2019-06-08T10:26:14Z

0 votes

基于@Cameron和@Neil的答案,我编写了一个扩展方法,它使用与Enumerable类相同的术语。

///

/// Determines whether a sequence contains the specified elements by using the default equality comparer.

///

/// The type of the elements of source.

/// A sequence in which to locate the values.

/// The values to locate in the sequence.

/// true if the source sequence contains elements that have the specified values; otherwise, false.

public static bool ContainsAll(this IEnumerable source, IEnumerable values)

{

return !values.Except(source).Any();

}

sclarke81 answered 2019-06-08T10:26:38Z

0 votes

在这里,我们检查子列表中是否存在任何元素(即t2),该列表未包含在父列表中(即t1)。如果不存在,则该列表是另一个的子集

例如:

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

Lucifer answered 2019-06-08T10:27:07Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值