c# - 大小写不变搜索字符串数组/列表中的字符串

标签 c# linq

以下代码可用于使用 LINQ 在数组/字符串列表中进行搜索。

String[] someArray
    = { "Test1", "test2", "test3", "TEST4" };

string toCheck = "Test1";

if (someArray.Any(toCheck.Contains))
{
    // found -> Do sth.
}
// or with list 

List<string> someList
    = new List<string>(new string[] { "TEST1", "test2", "test3", "TEST4"  });

if (someList.Any(toCheck.Contains))
{
    // "Test1" != "TEST1"
}

但是你怎么能做到这种大小写不变呢?

我的方法是将完整列表转换为上层列表,然后使用包含进行测试:

if ((someList.ConvertAll(item => item.ToUpper()).Any(toCheck.ToUpper().Contains)))
{
    // found -> Do sth.
}

在这种情况下,原始列表没有改变。

if ((someList.Select(item => item.ToUpper()).Any(toCheck.ToUpper().Contains)))
{
    // works with both
}

很好用...(还有一些特定于语言的东西,例如土耳其语的“i”字母...(据我所知,我们仍然没有土耳其语客户...但谁知道他们是不是是在未来?)),但它似乎不是很优雅。

如果一个项目在列表中,有没有办法进行大小写不变的比较?

最好的问候, 提供者

最佳答案

代替包含使用IndexOfStringComparison.OrdinalIgnoreCase :

String[] strings = { "Test1", "test2", "test3", "TEST4" };
String text = "TEST123";
if (strings.Any(str => text.IndexOf(str, StringComparison.OrdinalIgnoreCase) > -1))
{
    // we will enter this if clause
}

Demo

关于c# - 大小写不变搜索字符串数组/列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17039023/

相关文章:

c# - 如何更快/更智能地读取文本文件?

c# - 列表框不刷新?

c# - ReSharper 类型成员布局模式 - 分组事件处理程序

c# - 首先在 EF6 db 中模拟数据库

c# - System.Collections.Generic.Find() 与 Linq.First()

c# - LINQ Expression API 不提供创建变量的方法吗?

c# - 将 LINQ intersect 函数与非基本类型结合使用

c# - Tamir.SharpSsh 重定向输出 (Sha1)

c# - 从 linq 中的类返回可枚举值?

c# - 使用 Access DB 作为数据源进行 ORM 的最佳方法