Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq string compare with indexOf

I have a table that has a string field that holds hostnames. They are mostly fully qualified domain names but over the years the domain bits after the first "dot" have changed as various DNS changes have fallen on us. So I might have the machine "tom" that is in the table as:

tom.company.com
tom.it.company.com
tom.newComapnyBranding.com
...

I often have to do comparisons against the "current" host name and this historical store. Doing something like:

WHERE
    UPPER(SUBSTRING(@foo, 1, CHARINDEX(".", @foo))) = 
    UPPER(SUBSTRING(myDB.myTable.machineName, 1, CHARINDEX(".", myDB.myTable.machineName)))

Ok, I am trying to convert one of these into a Linq query but am stumbling on the "index" part. I have come as close as:

myTable.machineName.ToUpper().Substring(0, myTable.machineName.IndexOf("."))
    .Equals(foo.ToUpper().Substring(0, foo.IndexOf(".")))

but visual studio is complaining about "IndexOf". It claims that I need to change the IndexOf to:

IndexOf(".", StringComparison.Ordinal))

but when i run it I get the exception message:

LINQ to Entities does not recognize the method 'Int32 IndexOf(System.String,
System.StringComparison)' method, and this method cannot be translated into
a store expression

How do you do this kind of indexed based substring in Linq?

like image 640
7 Reeds Avatar asked Sep 21 '17 14:09

7 Reeds


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C language?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.


1 Answers

Expressions given to Entity Framework are restricted to ones that can be translated into SQL. EF doesn't know how to translate String.IndexOf into SQL.

You can instead use SqlFunctions.CharIndex:

SqlFunctions.CharIndex(machineName, ".")
like image 155
Cory Nelson Avatar answered Sep 27 '22 23:09

Cory Nelson