[英]why is string IndexOf() acting case-INsensitive?
I'm really stumped by this one. 我真的被这个难倒了。 I'm learning LINQ and used Microsoft Visual C# Express Edition to connect to a SQL Server database containing information about my books. 我正在学习LINQ并使用Microsoft Visual C#Express Edition连接到包含有关我的书籍信息的SQL Server数据库。 I created the LINQ to SQL classes as needed. 我根据需要创建了LINQ to SQL类。 That stuff obviously works. 那东西显然有效。 It all works except I cannot figure out for the life of me why, if I search for "SR" (uppercase), it finds two records, "SR-71 Revealed, The Inside Story", as expected, but it also finds "Faded Sun: Kesrith" where the "sr" is lowercase. 这一切都有效,除了我无法弄清楚为什么,如果我搜索“SR”(大写),它会找到两个记录,“SR-71 Revealed,The Inside Story”,如预期的那样,但它也发现“褪色太阳:Kesrith“其中”sr“是小写的。 I'm using the IndexOf() method of the string class, which is supposed to perform a case-SENSITIVE comparison, right? 我正在使用字符串类的IndexOf()方法,它应该执行case-SENSITIVE比较,对吧? The output displays the second book title as shown above, with the "sr" in lowercase. 输出显示第二个书名,如上所示,“sr”为小写。 Here's the pertinent part of the code: 这是代码的相关部分:
// normal using directives here
namespace QueryBooksDB {
class Program {
static void Main() {
var urgh = new BooksDataContext();
Console.WriteLine("Enter a string to search for:");
string str = Console.ReadLine();
var list = from book in urgh.Books
where book.Title.IndexOf(str) > -1
orderby book.Title
select new { ID = book.BookId, book.Title, book.Location };
foreach ( var b in list ) {
Console.WriteLine(b.Title);
}
}
}
}
At the final step your query is translated into sql. 在最后一步,您的查询将转换为sql。 In SQL server string alike fields (varchar, nvarchar) are case insensetive. 在SQL服务器字符串中,字段(varchar,nvarchar)是case insensetive。 So select * from tbl where col like '%foo%'
will retrieve if the value is Foo
or FOo
因此select * from tbl where col like '%foo%'
如果值为Foo
或FOo
select * from tbl where col like '%foo%'
将检索
I thought it was case-sensitive by default, but you can always use the StringComparison
overload to specify case sensitivity: 我认为默认情况下它区分大小写,但您始终可以使用StringComparison
重载来指定区分大小写:
test.IndexOf("foo", StringComparison.Ordinal);
StringComparison
enumeration: StringComparison
枚举:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.