C# -Linq: игнорировать регистр при сравнении с использованием string.equals в linq - PullRequest
0 голосов
/ 03 марта 2020

Как использовать 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)); 

1 Ответ

2 голосов
/ 03 марта 2020

Вы можете попробовать этот способ

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
...