C#Linq字符串与indexOf比较 [英] C# Linq string compare with indexOf

查看:215
本文介绍了C#Linq字符串与indexOf比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,该表具有一个包含主机名的字符串字段.它们大多是完全合格的域名,但是多年来,随着各种DNS更改的出现,第一个点"之后的域位已经更改.因此,表中的机器"tom"可能为:

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)))

好吧,我试图将其中之一转换为Linq查询,但在索引"部分遇到了麻烦.我已经接近:

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(".")))

,但是Visual Studio抱怨"IndexOf".它声称我需要将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

您如何在Linq中使用这种基于索引的子字符串?

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

推荐答案

提供给Entity Framework的表达式仅限于可以转换为SQL的表达式. EF不知道如何将String.IndexOf转换为SQL.

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.

您可以改为使用SqlFunctions.CharIndex:

SqlFunctions.CharIndex(machineName, ".")

这篇关于C#Linq字符串与indexOf比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆