C# 比较字符串值数组

C# Comparing an array of string values

我正在使用一种静态方法创建静态 class,该方法比较填充了用户输入选择的字符串和 "supposed to be the inputs";

的预定义数组

我关心的是预定义数组在 class 中的位置,以及要使用的正确数据类型实际上是数组还是字典。

我将在预定义中最多包含大约 150 个字符串,并准备好与字符串数组进行比较。

这是我目前的情况。

public static class SelectionMatchHelper
{
     static readonly string[] predefinedStrings = {"No answer", "Black", "Blonde"};
    public readonly static bool SelectionMatch(string[] stringsWeAreComparingAgainst, int validCount)
    {
        int numberOfMatches = 0;
         for (int x = 0; x < "length of string array"; x++)
                {
                    //will loop through and check if the value exists because the array to match against will not always have the same index length

                        numberOfMatches += 1;
                }
        numberOfMatches.Dump();
    if (numberOfMatches == 0 || numberOfMatches < validCount || numberOfMatches > validCount) return false;
                return true;
    }

}

这基本上是基于用户必须满足的参数数量,该方法获得匹配项,如果不等于该数量,则它 returns 错误。用户使用的输入是下拉菜单,因此这仅用于确保我的值在保存之前未被篡改。

我的问题是哪种数据类型最适合这种情况,字符串 array/list 还是字典?第二个问题是应该放在哪里以避免线程问题,在方法内部还是外部?

编辑 - 我只想补充一点,预定义值将保持不变,所以我最终会将该字段设置为只读常量值。

编辑 2 - 刚刚重新检查了我的代码,我不会使用 CompareOrdinal,因为我完全忘记了顺序很重要的部分。所以这将是一个关键的查找。所以我会删除方法的内部,这样人们就不会混淆了。主要问题还是一样。

感谢大家的帮助。

从可读性的角度来看,HashSet 是最好的类型,因为它专门用于 "item is present in the set"。

 static readonly HashSet<string> predefinedStrings = new HashSet<string>(
       new []{"No answer", "Black", "Blonde"}, 
       StringComparer.Ordinal);

if (predefinedStrings.Contains("bob"))....

幸运的是 HashSetthread safe for read-only operations,提供 O(1) 的检查时间并支持不区分大小写的比较,如果你需要的话。