简体   繁体   中英

Use indexOf() function in LINQ in vb.net or C#?

I have a table in database that it has a column name. I have to change all Items name when I read table before showing in Grid . I must to use this LINQ Clause

Dim hospitalList = From l In db_Obj.VWrmz_HospitalCorrection
                       Select hospitalName = l.HOSPITAL_NAME.Substring(0,l.HOSPITAL_NAME.IndexOf("--"))

when i use above code i get this error 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.

but when I remove IndexOf() its work correctly:

Dim hospitalList = From l In db_Obj.VWrmz_HospitalCorrection
                   Select hospitalName = l.HOSPITAL_NAME.Substring(10)

How can I do for remove something from my cells like this?

Using anonymous perhaps?

Dim hospitalList = From l In db_Obj.VWrmz_HospitalCorrection
                       Select New With {.hospitalName = l.HOSPITAL_NAME.Substring(0,l.HOSPITAL_NAME.IndexOf("--"))}

In your error message, the unrecognized method is "Int32.IndexOf", the invoker of "IndexOf" method is "Int32" instead of "String", is there any possible that your HOSPITAL_NAME can be a number ??

If you cannot find the problem, you can try the regular expressions instead of "Substring" method, like this(I am using C#, so... this is the c# code, sorry for that):

Regex regex = new Regex("--.*");
var hospitalList = From l In db_Obj.VWrmz_HospitalCorrection
                   Select hospitalName = regex.Replace(l.HOSPITAL_NAME, "");

Hope this can Help

Here is a C# version for it.
LINQ to EF cannot translate IndexOf method to sql syntax. You can fetch the data and perform the operation on it later.

from ll in (from l in db_Obj.VWrmz_HospitalCorrection
 select hospitalName = l.HOSPITAL_NAME).ToList()
 select ll.Substring(0, ll.IndexOf("--"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM