验证列表是否包含所有其他列表值

우두머*_*두머리 1 c# linq compare

我有2个int数组,arr1和arr2,例如,验证arr1包含arr2包含的所有项目的最有效方法是什么.优先归还bool.

例如.

arr1 = [1,2,3,4]
arr2 = [1,2,3,4,5,6,9]
 //return true;

arr1 = [1,2,3,4,10]
arr2 = [1,2,3,4,5,6,9]
 //return false;
Run Code Online (Sandbox Code Playgroud)

我做了它,foreach但除了蛮力的foreach,我想要任何东西,如果可能的话.

Sim*_*son 9

怎么样的:

bool subset = !arr1.Except(arr2).Any();
Run Code Online (Sandbox Code Playgroud)

可能会顺利实现为这样的扩展方法:

public static bool ContainsAll<T>(this List<T> list, List<T> other)
{
    return !other.Except(list).Any();
}
Run Code Online (Sandbox Code Playgroud)

用法将是:

bool subset = arr2.ContainsAll(arr1);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

147 次

最近记录:

10 年,8 月 前