Friday, January 15, 2010

Doing a 1-* OR without the ugly operators.

Many times I have found myself with an array of values not always in a list doing a comparison such as.

Dim myName as String = "Brian";
If myName = "Ryan" Or myString = "Todd" Or mystring = "Brian" Then _
DoMyFunction()

Ugly and repetitious with only 3 options.
You do have other options such as loading into a list and using a contains method, or you can also use the case method which I am not actually improves it.

Awhile back when I found out about extensions I realized that combined with generics I am able to produce something much cleaner that is very familiar if you have ever used SQL.

Here is the VB version, although it can easily be coded in C# just the same, unfortunately my current project that I am writing this post from is VB.

_
Public Function [In](Of T)(ByVal objCompareFrom As T, ByVal ParamArray objCompareTo As T()) As Boolean
For Each compareToSingle As T In objCompareTo
If objCompareFrom.Equals(compareToSingle) Then Return True
Next
Return False
End Function

Since it extends a generic type it is accessible from any object in your code base with type safety.
Using this method you end up with code that reads like this.

If myString.In("Ryan","Todd","Brian") Then _
DoMyFunction()

Now this is just a single one to many comparison, if you find the need you can extend the idea for a many to many evaluation or even a intersect and except operator.

No comments:

Post a Comment