C#-Linq:在linq中使用string.equals进行比较时忽略大小写

问题描述 投票:0回答:1

如何在下面的代码中使用StringComparison属性?

string _strVariable = "New York";
//nestList is nested list, list of list of objects, city below is an object, not a string 
var _countVar = nestList
  .SelectMany(list => list)
  .Count(city => string.Equals(city, _strVariable));

以下尝试过,但是它们不起作用,会引发错误。

var _countVar = nestList
  .SelectMany(list => list)
  .Count(city => string.Equals(city, _strVariable,StringComparison.OrdinalIgnoreCase));

var _countVar = nestList
  .SelectMany(list => list)
  .Count(city => string.Equals(city, _strVariable,StringComparer.OrdinalIgnoreCase)); 
c# linq string-comparison
1个回答
2
投票

您可以尝试这种方式

String.Equals(_strVariable, city, StringComparison.CurrentCultureIgnoreCase)

或使用.ToLower.ToUpper方法,但是,这不是引起性能问题的好方法。

city.ToUpper() == _strVariable.ToUpper()

更新

您无法将对象/自定义类型与字符串类型进行比较。您可以这样做

.Count(c => string.Equals(c.City, _strVariable,StringComparer.OrdinalIgnoreCase)
-- Let's say You want to compare the City or CityName with the _strVariable

0
投票

您可以尝试像这样在Equals中重写Count方法

.Count(city => city.Equals(_strVariable, StringComparison.OrdinalIgnoreCase));
© www.soinside.com 2019 - 2024. All rights reserved.