Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append a 'where' clause using VB.NET and LINQ?

I am pretty new to VB.NET and am having a bit of trouble here with something I thought should be simple.

Keeping it simple, let's say I have a Document table with "Name" that I want to search on (in reality there are several other tables, joins, etc. ..). I need to be able to build the query using a where clause based on string values passed in.

Example - the user may pass in "ABC", "ABC DEF", "ABC DEF GHI".

The final query would be (the syntax is not correct, I know):

Select * from Documents Where Name Like %ABC% AND Name Like %DEF% AND Name like %GHI% 

So, I thought I could do something like this.

Dim query = From document In _context.Documents  << loop based on number of strings passed in >> query = query.Where( ... what goes here?? ) 

For some reason, being brain-dead or something, I can't figure out how to make this work in VB.NET, or if I'm doing it correctly.

like image 630
sugarcrum Avatar asked Apr 23 '09 16:04

sugarcrum


People also ask

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

Does VB.NET have Linq?

This stands for Language Integrated Query. In VB.NET we import the System. Linq namespace—this provides many extension methods, ones that act on collections.

Where is Visual Basic?

The Where clause enables you to filter query data by selecting only elements that meet certain criteria. Elements whose values cause the Where clause to evaluate to True are included in the query result; other elements are excluded.


2 Answers

I believe this is how you would do it in VB (I'm a C# developer):

query = query.Where(Function(s) s = "ABC") 

See LINQ - Sample Queries for some examples.

like image 71
Jimmie R. Houts Avatar answered Sep 22 '22 20:09

Jimmie R. Houts


I think the tricky part here is the unknown number of query parameters. You can use the underlying LINQ IQueryable(Of T) here to help.

I think the following would work (it's not compiled, just notepad code here):

Public Function GetDocuments(criteria as String)     Dim splitCriteria = SplitTheCriteria(criteria)      dim query = from document in _context.Documents      For Each item in splitCriteria         Dim localItem = item         query = AddCriteriaToQuery(query, localItem)     Next      dim matchingDocuments = query.ToList() End Function  Private Function AddCriteriaToQuery(query as IQueryable(Of Document), criteria as string) as IQueryable(Of Document)      return query.Where(Function(doc) doc.Name = criteria) End Function 

Since LINQ will delay-execute the query you can append where clauses onto your query in the loop and then call .ToList() at the end to execute the query.

like image 40
Jeremy Wiebe Avatar answered Sep 26 '22 20:09

Jeremy Wiebe