DeSon
DeSon

Reputation: 147

C#-Linq: Ignore case when comparing using string.equals in linq

How to use StringComparison properties in the below code?

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));

Tried below but they don't work, throws an error.

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)); 

Upvotes: 0

Views: 909

Answers (1)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14198

You can try this way

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

Or use .ToLower or .ToUpper method, However, It's not a good way to cause the performance problem.

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

Updated

You can not compare object / custome type with a string type. You can do this

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

Upvotes: 2

Related Questions