Problem
Background Story: I am rewriting all SQL queries of legacy system into LINQ.
The database is not as clean as I expect. As many of these SQL record contains spaces or different cases which treated as the same.
SELECT *
FROM fruit
WHERE name = @fruitname;
Provided @fruitname
is apple
, this query will match any record ends with apple
, _apple
, APPLE_
(where _
is a whitespace character).
However, This is the expected behavior in my use cases.
On the otherhand, LINQ string comparison is more precise. Which annoys me because such issues keep surfacing to me.
Setup
FruitTableAdapter fruitsAdapter = new FruitTableAdapter();
MyGardenDataSet.FruitDataTable fruitsTable = fruitsAdapter.GetData();
Approaches
// Issue 1: Does not match, '_apple' or 'APPLE_'
var fruits1 = fruitsTable.Where(row=>row.name == fruitname);
// Issue 2: String Comparison with case insensitive (does not match 'APPLE')
var fruits2 = fruitsTable.Where(
row=>row.nameEquals(fruitname, StringComparison.OrdinalIgnoreCase));
// Issue 3: Trailing space with case insensitive
var fruits2 = fruitsTable.Where(
row=>row.name.Trim().Equals(fruitname.Trim(),
StringComparison.OrdinalIgnoreCase));
I'm not sure but there could be many issues which SQL query are different from String Comparison.
Is there any SQL aware StringComparison? How can I achieve the same string comparison as SQL in LINQ?