C# 中是否有类似 VB.NET 的运算符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24812662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a VB.NET-Like operator in C#?
提问by Robert
I am rewriting a vb.net app and I can't claim to be great with vb. I need to write this equivilent in C#:
我正在重写一个 vb.net 应用程序,但我不能声称自己很擅长 vb。我需要在 C# 中编写这个等效项:
Dim bigList = (From gme In dtx.gmc_message_elements
Where gme.element_key_name Like "*email" _
Or gme.element_key_name Like "*web"
Or gme.element_key_name Like "*both" _
Select gme.element_key_name Distinct).ToList()
I have so far:
我到目前为止:
var bigList = (from gme in dtx.gmc_message_elements
where gme.element_key_name Like "*email"
|| gme.element_key_name Like "*web"
|| gme.element_key_name Like "*both"
select gme.element_key_name).FirstOrDefault().ToList();
As you can see I am not sure what the equivalent of the like operator is. I ran this through a couple code converters and they constantly threw errors.
如您所见,我不确定 like 运算符的等价物是什么。我通过几个代码转换器运行了这个,他们不断地抛出错误。
回答by Lukazoid
To get the most equivalent functionality ensure your C# project has a reference to the Microsoft.VisualBasic assembly.
要获得最等效的功能,请确保您的 C# 项目具有对 Microsoft.VisualBasic 程序集的引用。
You can then directly use the VB.NET Likeoperator from your C#, e.g.
然后,您可以直接使用LikeC# 中的 VB.NET运算符,例如
LikeOperator.LikeString(gme.element_key_name, "*web", CompareMethod.Text);
Be sure to include the
务必包括
using Microsoft.VisualBasic.CompilerServices;
This will get the most equivalent functionality, however would be what I consider a bit of a hack.
这将获得最等效的功能,但是我认为这有点小技巧。
Your other options would be to make use of the String.StartsWith, String.EndsWith, String.Containsor Regex.
您的其他选项将是利用的String.StartsWith,String.EndsWith,String.Contains或正则表达式。
回答by Amir Popovich
Use StartsWithor EndsWithor Containsstatic methods of stringbased on your needs.
根据您的需要使用StartsWith或EndsWith或Contains静态方法string。
回答by ketan Shah
I think Regex is the best option. Since the Like operation supports *,?, # and [], I think there can be complex patterns possible which can be matched easily using the Regex library. For eg. the following lines will return true.
我认为正则表达式是最好的选择。由于 Like 操作支持 *、?、# 和 [],我认为可以使用 Regex 库轻松匹配复杂的模式。例如。以下几行将返回 true。
"aBBBa" Like "a*a"
"ajhfgZ1" Like "*Z[12]"
"aBBBa" Like "a*a"
"ajhfgZ1" Like "*Z[12]"
Now it depends on your application. If you are just using it to match a simple hardcoded string , you can directly use String.Contains, String,StartsWith or String.EndsWith but for complex matching use Regex for the best results.
现在这取决于您的应用程序。如果你只是用它来匹配一个简单的硬编码字符串,你可以直接使用 String.Contains、String、StartsWith 或 String.EndsWith 但对于复杂的匹配使用 Regex 以获得最佳结果。

