为什么 string IndexOf() 不区分大小写?
我真的被这个难住了。我正在学习 LINQ 并使用 Microsoft Visual C# Express Edition 连接到包含我的图书信息的 SQL Server 数据库。我根据需要创建了 LINQ to SQL 类。那东西显然有效。这一切都有效,只是我无法弄清楚为什么,如果我搜索“SR”(大写),它会找到两条记录,“SR-71 Revealed,The Inside Story”,如预期的那样,但它也找到“褪色的太阳:Kesrith”,其中“sr”是小写的。我正在使用字符串类的 IndexOf() 方法,该方法应该执行区分大小写的比较,对吧?输出显示第二本书的标题,如上所示,其中“sr”为小写。这是代码的相关部分:
// 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);
}
}
}
}
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. I created the LINQ to SQL classes as needed. 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. I'm using the IndexOf() method of the string class, which is supposed to perform a case-SENSITIVE comparison, right? The output displays the second book title as shown above, with the "sr" in lowercase. 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);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在最后一步,您的查询将转换为 sql。在 SQL Server 中,字符串类似字段(varchar、nvarchar)不区分大小写。所以
select * from tbl where col like '%foo%'
如果值为Foo
或FOo
将检索At the final step your query is translated into sql. In SQL server string alike fields (varchar, nvarchar) are case insensetive. So
select * from tbl where col like '%foo%'
will retrieve if the value isFoo
orFOo
我认为它默认区分大小写,但您始终可以使用
StringComparison
重载来指定区分大小写:StringComparison
enumeration:I thought it was case-sensitive by default, but you can always use the
StringComparison
overload to specify case sensitivity:StringComparison
enumeration: