-1

I have a very simple Linq-to-SQL query that returns a boolean:

using (MyDataContext TheDC = new MyModelDataContext())
{
    return !TheDC.SomeTable.Any(l => l.UserID == SomeLong && l.ColumnName == SomeString);
}

The problem is that when the comparison involves strings that differ by the case of some letters, it returns false. For instance, if the table contains testString and SomeString is TestString, it returns false.

How can I rewrite it?

frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

-1

You have the Equal funcion

in your case it's should look like this:

using (MyDataContext TheDC = new MyModelDataContext())
{
    return !TheDC.SomeTable.Any(l => l.UserID == SomeLong && l.ColumnNameEquals(SomeString, StringComparison.InvariantCultureIgnoreCase));
}
Tom Mendelson
  • 625
  • 4
  • 10
  • This is just a variation on the other **strongly** downvoted answers, and probably doesn't make it through the linq2sql translation to SQL. Are you sure you want to post this? – spender Mar 13 '18 at 15:52
  • 1
    @spender Unlike other answers this simply doesn't do a case insensitive comparison. LINQ to sql knows how to interpret this code, it just ignores the comparison operator and uses the DB's collation settings regardless. So this answer is actually bad for very different reasons than the other answers. – Servy Mar 13 '18 at 15:54
  • i'm pretty sure it's the best answer to this weird case. btw, this question marked as duplicated, i recommend you to watch the answer over there :) – Tom Mendelson Mar 13 '18 at 15:58
  • @TomMendelson Why do you think an answer that doesn't actually work is the best answer? – Servy Mar 13 '18 at 16:00
-4

Would you like to try this code?

using (MyDataContext TheDC = new MyModelDataContext())
{
    return !TheDC.SomeTable.Any(l => l.UserID == SomeLong && l.ColumnName.ToLower() == SomeString.ToLower());
}
Minos
  • 218
  • 2
  • 7
  • an awesome way to destroy index – Steve Mar 13 '18 at 15:33
  • wow. Of course, if you think about performance, index or full text search should be considered. And it is not copied. The answer was only slow. – Minos Mar 13 '18 at 15:37
  • index/full text search will get destroyed completely if you are doing .ToLower(). – Steve Mar 13 '18 at 15:48
  • I agree with your answer. I just thought that the questioner would have asked the C# code rather than the DB. – Minos Mar 13 '18 at 15:57
  • I think the answer to this question about performance may be an over-answer to the question. Of course, simple answer is to add a lower-cased column to the DB. – Minos Mar 13 '18 at 16:06
-4

I'd try, tolower() and for good measure check the db collate.

l.ColumnName.ToLower() == SomeString.ToLower()
Rickey
  • 7,830
  • 1
  • 19
  • 12