use*_*811 1 c# arrays ienumerable
通过给出一个字符串数组,我想测试数组中的每个元素是否包含在预定义的字符串数组中.
例如:
var a = new[] { "test1", "test2" };
var b = new[] { "test1", "test4" };
var c = new[] { "test1", "test3", "test1", "test3" };
var predefined = new[] { "test1", "test2", "test3" };
Run Code Online (Sandbox Code Playgroud)
变量a和c将返回true,b将返回false.
C#代码最有效的方法是什么?
订购对您有用吗?如果没有,我只使用LINQ:
if (!a.Except(predefined).Any())
{
// predefined contains every element of a
// (Way to read this: there is no element of a which isn't also in predefined)
}
Run Code Online (Sandbox Code Playgroud)
这通常是O(N + M),而不是All...... ContainsO(N*M)的解决方案.当然,这并不表示绝对的表现.如果您使用的是小型集合,那么All...... Contains实际上可能会更快.随着涉及的集合越来越大,这种情况更有可能更快.
编辑:如评论中所述,如果你可以创建一个HashSet<T>from predefined并重用它,它可以更有效......而且实际上更具可读性:
var predefinedSet = new HashSet<string>(predefined);
...
if (predefinedSet.IsSupersetOf(a))
{
...
}
Run Code Online (Sandbox Code Playgroud)