Select 按字符串相似度枚举值

Select enum value by string similarity

我有一个包含六个不同值的枚举:

一个 二 三 四 五 六个

从配置文件(即字符串)填充

假设有人将任何值写入配置文件

或其他常见的 misspellings/typos,我想从枚举中设置最相似的值(在本例中,"One")而不是抛出。

C# 是否有类似内置的东西,或者我是否必须为 C# 调整现有的编辑距离算法并将其挂接到枚举中?

您可以使用 Levinshtein distance,这告诉我们将一个字符串转换为另一个字符串所需的编辑次数:

所以只需遍历枚举中的所有值并计算 Levinshtein 距离:

private static int CalcLevenshteinDistance(string a, string b)
{
    if (String.IsNullOrEmpty(a) || String.IsNullOrEmpty(b)) return 0;

    int lengthA = a.Length;
    int lengthB = b.Length;
    var distances = new int[lengthA + 1, lengthB + 1];
    for (int i = 0; i <= lengthA; distances[i, 0] = i++) ;
    for (int j = 0; j <= lengthB; distances[0, j] = j++) ;

    for (int i = 1; i <= lengthA; i++)
        for (int j = 1; j <= lengthB; j++)
        {
            int cost = b[j - 1] == a[i - 1] ? 0 : 1;
            distances[i, j] = Math.Min
                (
                Math.Min(distances[i - 1, j] + 1, distances[i, j - 1] + 1),
                distances[i - 1, j - 1] + cost
                );
        }
    return distances[lengthA, lengthB];
}