12

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#:

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.

6
  • What is the source you're querying? .Where(x => x.EndsWith("email"); might be appropriate. Commented Jul 17, 2014 at 20:14
  • There's no Like operator in C#, in this case you can use String.EndsWith(if this is Linq-To-Objects), otherwise you need to use regex or SqlMethods.Like( if it's Linq-To-Sql ). Commented Jul 17, 2014 at 20:14
  • This question is not a duplicate, this concerns converting the VB.NET Like operator to a C# equivalent whereas the other question is the SQL LIKE operator, different things... Commented Jul 17, 2014 at 20:18
  • @Robert: it's at the top of your post (perhaps you need to refresh) Commented Jul 17, 2014 at 20:20
  • 1
    It is possible to achieve the same in C# but you don't get the same syntactic sugar, so it's a bit ugly: where LikeOperator.LikeString(mySourceString, "*Something*", CompareMethod.Text) It's in the Microsoft.VisualBasic.CompilerServices namespace. Further info here: msdn.microsoft.com/en-us/library/… Commented Jul 17, 2014 at 20:26

5 Answers 5

23

To get the most equivalent functionality ensure your C# project has a reference to the Microsoft.VisualBasic assembly.

You can then directly use the VB.NET Like operator from your C#, e.g.

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.Contains or Regex.

Sign up to request clarification or add additional context in comments.

1 Comment

NOTE: For anyone who will try to write Microsoft.VisualBasic.CompilerServices.. Note a . in the end. When you press it, you won't see any IntelliSense tip. It's OK - just continue typing LikeOperator. And when you press . after it, you'll finally get IntelliSense with LikeString and LikeObject methods. Same goes when you use using Microsoft.VisualBasic.CompilerServices;.
5

Use StartsWith or EndsWith or Contains static methods of string based on your needs.

2 Comments

Those methods don't allow for wildcard characters the way Like does
Also those are not static methods.
0

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.

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

3 Comments

You should probably add the actual regexes that you suggest. If you're trying to say *Z[12] is a regular expression, that's wrong. a*a also doesn't match aBBBa--it only matches 0 or more as then another a. You may have meant a.*a and Z[12]. (Or you may have only been trying to demonstrate Like syntax, but this is unclear to me.)
hiii the a*a does match aBBBa . And the the the "Like" operation matches patterns with strings, so the pattern part of the equation does support * , ? and etc. and *Z[12] can be converted to a regular expression i meant, but for LIKE operation that is the way it can be used. More info on this is at msdn.microsoft.com/en-us/library/swf8kaxw.aspx Anyways feel free to correct me if I'm wrong. Thats how i'll learn :)
Ok, my complaint is really just that it's unclear what your example means. which can be matched easily using the Regex library. For eg. the following lines will return true. leads me to believe the next few lines will have regular expressions. Pointing out that you're giving the examples just to show that Like is complex would clear it up I think.
0

As already pointed out by others there is no Like operator in C#.

Also it is not available in VB.Net for .net standard. (It has been added again for .net)

I had the case that the pattern is a user input. Migrating to net standard, my only option was therefor to implement it myself. I chose to convert the pattern to an equivalent regular expression:

<Extension()> Public Function VbLike(str As String, pattern As String) As Boolean Dim resultPattern = New Text.StringBuilder Dim insideList = False Dim prevInsideList = False For i = 0 To pattern.Length - 1 Dim c = pattern(i) Dim tempInsideList = insideList ' Manage pattern start If i = 0 AndAlso c <> "*"c Then resultPattern.Append("^"c) End If ' Manage characterlists If c = "["c AndAlso Not insideList Then insideList = True resultPattern.Append(c) ElseIf c = "]"c AndAlso insideList Then insideList = False resultPattern.Append(c) ' Special chars for Like that need to be converted ElseIf c = "!"c AndAlso insideList AndAlso Not prevInsideList Then resultPattern.Append("^"c) ElseIf c = "?"c AndAlso Not insideList Then resultPattern.Append("."c) ElseIf c = "#"c AndAlso Not insideList Then resultPattern.Append("\d") ElseIf c = "*"c AndAlso i = 0 Then ' Nothing to append ElseIf c = "*"c AndAlso i = pattern.Length - 1 Then ' Nothing to append ElseIf c = "*"c AndAlso Not insideList Then resultPattern.Append(".*") ' Special chars for Regex that need to be escaped ElseIf c = "."c OrElse c = "\"c OrElse c = "("c OrElse c = ")"c Then resultPattern.Append("\"c) resultPattern.Append(c) Else resultPattern.Append(c) End If ' Manage pattern end If i = pattern.Length - 1 AndAlso c <> "*"c Then resultPattern.Append("$"c) End If prevInsideList = tempInsideList Next Return Regex.IsMatch(str, resultPattern.ToString, RegexOptions.Singleline Or RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant) End Function 

Comments

0

Here is Eric Pitz' VbLike code converted to C#, because the original poster was trying to re-create this function in C#.

public bool VbLike(string str, string pattern) { var resultPattern = new System.Text.StringBuilder(); var insideList = false; var prevInsideList = false; for (var i = 0; i < pattern.Length; i++) { var c = pattern[i]; var tempInsideList = insideList; // Manage pattern start if (i == 0 && c != '*') { resultPattern.Append('^'); } // Manage characterlists if (c == '[' && !insideList) { insideList = true; resultPattern.Append(c); } else if (c == ']' && insideList) { insideList = false; resultPattern.Append(c); } else if (c == '!' && insideList && !prevInsideList) { // Special chars for Like that need to be converted resultPattern.Append('^'); } else if (c == '?' && !insideList) { resultPattern.Append('.'); } else if (c == '#' && !insideList) { resultPattern.Append(@"\d"); } else if (c == '*' && i == 0) { // Nothing to append } else if (c == '*' && i == pattern.Length - 1) { // Nothing to append } else if (c == '*' && !insideList) { resultPattern.Append(".*"); } else if (c == '.' || c == '\\' || c == '(' || c == ')') { // Special chars for Regex that need to be escaped resultPattern.Append('\\'); resultPattern.Append(c); } else { resultPattern.Append(c); } // Manage pattern end if (i == pattern.Length - 1 && c != '*') { resultPattern.Append('$'); } prevInsideList = tempInsideList; } return System.Text.RegularExpressions.Regex.IsMatch(str, resultPattern.ToString(), System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant); } 

1 Comment

Unfortunately, this is just as inapplicable as the answer you refer to, because the question is obviously about LINQ-to-SQL, where Regex.IsMatch is not supported.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.