Kai
Kai

Reputation: 2168

VB.NET: Writing a function that take specific-type, multiple key-value parameters

I'm trying to write a function in a basic MVC (experimental project) that should be called with the following (or as close to):

datastore = myTable.FetchData({{column1, constraint1}, 
                  {column2, constraint2}, ... 
                  {colN, conN}})

Function purpose - It queries a table with the constraints passed to it. For example,

FetchData({{Me.Fields("Price"), "<100"}, {Me.Fields("Type"), "=Component"}})

will ultimately produce the query

SELECT * FROM table a WHERE Price < 100 AND Type = "Component"

(the query production is more involved than that, involving relationships defined and so forth, but that's outside the scope of this question)

How should I write the function definition to take these parameters?

`Public Function FetchData( ??? ) As foobar

Essentially, it will be something similar to a Dictionary, since it's a list of pairs of values. However, it needs to be non-unique (it could be called to produce col1 > 1 AND col1 < 5 for eg). A two-dimensional arraylist has been considered also, but each half of the pair needs to be a specific type - the 'key' needs to be of my ColumnDefinition object type or string, the 'value' should always be a string.

What would be the best way to handle this?

Bonus question: merging the operator in with the constraint ("=component") seems ugly. Any idea about how to write the function def with the operator separate? I tried an enum but that just made it too verbose - I want this to be a fairly easy to use library.

Upvotes: 1

Views: 905

Answers (2)

Andre Pageot
Andre Pageot

Reputation: 336

Or according to the shape of the function call you are describing, if you are definitely using strings, and it is always {"Col", "Constraint"} then you could do this

Public Function FetchData(ByVal MultiDimensionArray(,) As String)
    'this is then how you could pull the pairs of cols and constraints back out
    'where n is the col constraint pair count up to (n) number
    For n As Integer = 0 To MultiDimensionArray.Length - 1
        Dim Col As String = MultiDimensionArray(0, n)
        Dim Constraint As String = = MultiDimensionArray(1, n)
    Next
End Function

Upvotes: 0

Channs
Channs

Reputation: 2101

If you are on .NET 4.0 or higher, suggest trying out the Tuple class to represent your queries. Your code may look like below.

Public Function FetchData(ByVal params As List(Of Tuple(Of ColumnDefinition, Char, String))) As foobar

Tuples are only recommended for API's under your control, where the context is obvious. If this is a public or shared API, suggest creating a named class with appropriate properties (as in Nico Schertler's comment). Then, the code may look like.

Public Function FetchData(ByVal params As List(Of MyContainerClass)) As foobar

Hope this helps.

Upvotes: 2

Related Questions