为什么字符串IndexOf()不区分大小写? [英] why is string IndexOf() acting case-INsensitive?

查看:671
本文介绍了为什么字符串IndexOf()不区分大小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的为这个感到难过.我正在学习LINQ,并使用Microsoft Visual C#Express Edition连接到包含有关我的书籍信息的SQL Server数据库.我根据需要创建了LINQ to SQL类.这些东西显然有效.一切正常,但我无法确定自己的一生,为什么,如果我搜索"SR"(大写字母),它会找到两条记录,即"SR-71 Revealed,The Inside Story",正如预期的那样,但是还会发现褪色的太阳:Kesrith","sr"为小写.我正在使用字符串类的IndexOf()方法,该方法应该执行区分大小写的比较,对吗?输出显示如上所示的第二本书的书名,其中"sr"为小写.这是代码的相关部分:

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);
            }
        }
    }
}

推荐答案

在最后一步,您的查询将转换为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 is Foo or FOo

这篇关于为什么字符串IndexOf()不区分大小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆