c# - linq 不区分大小写和修剪比较

标签 c# linq

我正在使用 linq 来查询表。

我的查询过滤器需要比较一些字符串值 - 这种比较不区分大小写并修剪空格,不仅在字符串的开头和结尾,而且在中间,例如。 “重庆”“四川”。我试图解决这个问题,但我发现它不起作用。

string fromLocation = this.uiFromLocation.Text;
string toLocation = this.uiToLocation.Text;
fromLocation = fromLocation.Trim().ToUpper();
toLocation = toLocation.Trim().ToUpper();

 var results = from myRow in sectionsDetails.Tables[0].AsEnumerable()
                              where myRow.Field<string>("LocationFrom").Trim().ToUpper() == fromLocation &&
                              myRow.Field<string>("LocationTo").Trim().ToUpper() == toLocation &&
                              myRow.Field<int>("VehicleType") == vehicleType
                              orderby myRow.Field<DateTime>("ModifiedDate") descending
                              select myRow;

我猜

myRow.Field<string>("LocationFrom").Trim().ToUpper() == fromLocation

不正确吗?

我该如何完成这项工作?

最佳答案

Trim() 仅修剪字符串开头和结尾(前导和尾随)的空格...参见 docs

要删除字符串中的空格,您可以使用:

  • *str*.Replace("", "");
  • Regex.Replace(*str*, @"\s", "")

其中 str 是字符串。

还可以考虑使用比较方法,例如 *str*.Equals(*str2*, StringComparison.OrdinalIgnoreCase),而不是依赖 ToUpper()。阅读 How to compare strings in C# ,详细解释了字符串比较。

关于c# - linq 不区分大小写和修剪比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56128316/

相关文章:

c# - 以 JSON 形式返回 Entity Framework 结果

c# - F# Array.choose id 在 C# 中等效

c# - Sharepoint 2010 - 自定义功能区

c# - NHibernate Linq 在 IQueryable 上使用 Between 子句

c# - Linq 返回没有跟进记录的记录

c# - 为什么使用 Lockbits 编辑图像仍然需要 7 秒?

c# - Linq查询OrderBy多个

c# - 无效操作异常 : An exception was thrown while attempting to evaluate a LINQ query parameter expression

c# - 对多种 Material 应用不同的纹理(Unity3D)

c# - 在添加迁移期间忽略来自引用程序集的实体