【问题标题】:How to ignore the case sensitivity in List<string> while calculating of an index of an entry [duplicate]如何在计算条目索引时忽略 List<string> 中的大小写敏感性 [重复]
【发布时间】:2015-04-25 23:22:35
【问题描述】:

假设我有这个代码:

private readonly static List<string> ExtPos = new List<string> {".dat", ".wef"};

private static int ExtToPos(string ext)
{
    return ExtPos.IndexOf(ext /*, StringComparer.InvariantCultureIgnoreCase*/);
}

如何在内容搜索中忽略字母大小写?

谢谢

【问题讨论】:

    标签: c#


    【解决方案1】:

    你可以使用FindIndex:

    int ix = ExtPos.FindIndex(x => ".DAT".Equals(x, StringComparison.CurrentCultureIgnoreCase));
    

    或者您可以使用StringComparer:它对null 更“抗性”(注意我是如何构建previos 比较的:我将“100% not-null,因为它是一个固定字符串”值放在左侧Equals!)

    int ix = ExtPos.FindIndex(x => StringComparer.CurrentCultureIgnoreCase.Equals(".DAT", x));
    

    【讨论】:

    • FindIndex 完美运行,谢谢! (我得到 String.Compare(ext, x, StringComparison.CurrentCultureIgnoreCase) == 0 作为谓词)
    • @Georg 使用Compare 然后== 0 感觉有点不对劲。在这种情况下最好使用Equals(它会立即返回bool)。您可以考虑使用OrdinalIgnoreCase。字符串相等检查的默认值是序号比较,所以如果你想要“像通常一样的相等,只区分大小写”,你可能更喜欢OrdinalIgnoreCase
    • 没错,Compare == 0 看起来有点奇怪,“Equals”对于申请者来说要好得多。 “CurrentCultureIgnoreCase”我不幸取自 xanatos,通常我使用更快的序数比较。
    【解决方案2】:

    使用FindIndex method。像这样:

    private static int ExtToPos(string ext)
    {
        return ExtPos.FindIndex(_ => 
            string.Equals(_, ext, StringComparison.InvariantCultureIgnoreCase));
    }
    

    【讨论】:

    • 在哪个框架版本中?我使用的是 .NET 4.0,无法将 lambda 函数传递给 IndexOf 函数。
    • @Georg:对不起。应该说FindIndex。我已经更新了我的答案。
    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2011-06-11
    • 1970-01-01
    • 2023-03-24
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多