我正在使用 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/