如何在下面的代码中使用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));
您可以尝试这种方式
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
您可以尝试像这样在Equals
中重写Count
方法
.Count(city => city.Equals(_strVariable, StringComparison.OrdinalIgnoreCase));