want_to_be_calm
want_to_be_calm

Reputation: 1637

linq case insensitive and trimmed comparison

I am using linq to query a table.

My query filters need to compare a few string values - this comparison is case insensitive and trimmed of white spaces, not just at the start and at the end of my strings but also in the middle eg. "chong qing" or "si chuan". I have tried to solve this but I found it is not working.

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;

I guess

myRow.Field<string>("LocationFrom").Trim().ToUpper() == fromLocation

is not correct?

How do I make this work?

Upvotes: 2

Views: 660

Answers (1)

Leo
Leo

Reputation: 5142

Trim() only trims white spaces at the start and end (leading and trailing) of the string... See docs

To remove white spaces within a string you can use:

  • *str*.Replace(" ", "");
  • Regex.Replace(*str*, @"\s", "")

where str is the string.

Also consider using a comparison method such as *str*.Equals(*str2*, StringComparison.OrdinalIgnoreCase) instead of relying on ToUpper(). Read How to compare strings in C#, it explains string comparison in detail.

Upvotes: 2

Related Questions