比较字符串时如何忽略大小写?

我正在使用linq搜索列表(用户在文本框中输入查询)。

我希望这个不区分大小写,并尝试使用IgnoreCase,但我不知道在哪里放它….我知道我可以使用大写或更低,但我想听听是否有人有任何替代方法? 什么是最佳做法? 正则表达式似乎也没有用?

string searchQuery = tbSearchQuery.Text; var something= from x in y where x.Subject.Contains(searchQuery) select x; 

使用string.Compare :

  var something= from x in y where string.Compare(x.Subject, searchQuery, true) >= 0 select x; 

这也可以处理任何字符串为空的情况。

由于还没有其他人提出它,我建议使用静态String.Equals,这样你就不必担心null并只返回你想要的信息。

String.Compare也可以工作,但你不是要对字符串进行排序(整数返回值的原因),只是在不区分大小写的比较中确定它们是否相等。

 var something = from x in y where string.Equals(x.Subject, searchQuery, StringComparison.CurrentCultureIgnoreCase) select x; 
 string searchQuery = tbSearchQuery.Text; var something= from x in y where x.Subject.IndexOf(searchQuery, StringComparison.OrdinalIgnoreCase) >= 0 select x; 

我使用以下自己的扩展(对于普通字符串)

  public static bool Contains(this string source, string toCheck, StringComparison comp) { return source.IndexOf(toCheck, comp) >= 0; } public static bool ContainsIgnoreCase(this string source, string toCheck) { return source.IndexOf(toCheck, StringComparison.InvariantCultureIgnoreCase) >= 0; } 

HTH

尝试

 string searchQuery = tbSearchQuery.Text; var something= from x in y where x.Subject.IndexOf(searchQuery, StringComparison.OrdinalIgnoreCase) != -1 

如果您使用的是LINQ-to-SQLEntity Framework ,则会在表定义中修复并设置排序规则。 比较它们的唯一方法是ToUpper (或ToLower ,但最好是ToUpper如http://www.siao2.com/2007/10/01/5218976.aspx所述 )这两部分比较。

你能使用IndexOf吗?

 string searchQuery = tbSearchQuery.Text; var something= from x in y where x.Subject.IndexOf(searchQuery, StringComparison.OrdinalIgnoreCase) >= 0 select x; 

我是第二种扩展方法。 我有一个课我用。 只需在你的项目中加入它并引用你的名字空间就可以了。

 using System; namespace YOUR NAME SPACE { public static class StringExtensionMethods { ///  /// Extention method to allow a string comparison where you can supply the comparison type /// (ie ignore case, etc). ///  /// The compare string. /// The comparison type - enum, use OrdinalIgnoreCase to ignore case. /// Returns true if the string is present within the original string.  public static bool Contains(this string original, string value, StringComparison comparisionType) { return original.IndexOf(value, comparisionType) >= 0; } } } 

这是使用它的LINQ查询的示例:

 var results = from promotion in response where String.IsNullOrEmpty(find.Code) || (promotion.Code != null && promotion.Code.Contains(find.Code, StringComparison.OrdinalIgnoreCase)) where String.IsNullOrEmpty(find.Name) || (promotion.Name != null && promotion.Name.Contains(find.Name, StringComparison.OrdinalIgnoreCase)) select promotion;