LINQ 中的 LIKE 运算符 [英] LIKE operator in LINQ
问题描述
有什么方法可以比较类似于 SQL 的 LIKE
运算符的 C# LINQ 表达式中的字符串?
Is there any way to compare strings in a C# LINQ expression similar to SQL's LIKE
operator?
假设我有一个字符串列表.在这个列表中,我想搜索一个字符串.在 SQL 中,我可以这样写:
Suppose I have a string list. On this list I want to search a string. In SQL, I could write:
SELECT * FROM DischargePort WHERE PortName LIKE '%BALTIMORE%'
与上面的不同,查询需要 linq 语法.
Instead of the above, query want a linq syntax.
using System.Text.RegularExpressions;
…
var regex = new Regex(sDischargePort, RegexOptions.IgnoreCase);
var sPortCode = Database.DischargePorts
.Where(p => regex.IsMatch(p.PortName))
.Single().PortCode;
我上面的 LINQ 语法不起作用.我做错了什么?
My above LINQ syntax does not work. What have I got wrong?
推荐答案
通常使用 String.StartsWith
/EndsWith
/Contains
.例如:
Typically you use String.StartsWith
/EndsWith
/Contains
. For example:
var portCode = Database.DischargePorts
.Where(p => p.PortName.Contains("BALTIMORE"))
.Single()
.PortCode;
我不知道是否有办法通过 LINQ to SQL 执行正确的正则表达式.(请注意,它确实取决于您使用的提供程序 - 在 LINQ to Objects 中会很好;这是提供程序是否可以将调用转换为其本机查询格式,例如 SQL.)
I don't know if there's a way of doing proper regular expressions via LINQ to SQL though. (Note that it really does depend on which provider you're using - it would be fine in LINQ to Objects; it's a matter of whether the provider can convert the call into its native query format, e.g. SQL.)
正如 BitKFu 所说,Single
应该在您期望 恰好一个 结果时使用 - 当情况并非如此是错误时.SingleOrDefault
、FirstOrDefault
或 First
的选项应该根据正是的预期使用.
As BitKFu says, Single
should be used when you expect exactly one result - when it's an error for that not to be the case. Options of SingleOrDefault
, FirstOrDefault
or First
should be used depending on exactly what's expected.
这篇关于LINQ 中的 LIKE 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!