Between the multiple advantages which offers LINQ I think there’s the possibility of reselect some data you have in cache or RAM so you don’t need to send another request to the database. I was programming a little personal application in VB.Net yesterday and found myself with a little problem.
I am saving some data encoded in base64 in the database and I want to have the option to filter and show only the ones which match. The problem came when I realized that, of course, having the data encoded in the Access DB I couldn’t just use a “LIKE” to filter the selection, since the characters are not as they really are.
First of all I thought on decoding the data in the DB and then filter but I do not know that much about Access DB to know how to do that and then LINQ came to my mind and realized I could just select the data, decode it, and reselect it using LINQ. And it worked! Much less code and time wasted, despite maybe not the most efficient method, it is just a little program for personal use.
First of all, I had that project just lost around my docs since some years and I had to convert the project from framework 2.0 to 3.5 for using LINQ libraries. Open the project, then Project -> Properties -> Compile tab -> Advanced Options -> .Net Framework version.
Second, I had to add the references for using LINQ, you can do this with an imports in the place you are going to use it or going to Project -> References -> .Net -> System.Core, and for converting an Array to an IEnumerable, you will need to add the System.Data.DataSetExtensions reference too.
Now you can use LINQ in your project and try to do something like this:
Private Sub showMangas() Dim filter As String = TXTMangaFilter.Text Dim dtMangas As DataTable = BBDDOle.getTable("SELECT idmanga, title FROM mangas", rutaBD) If dtMangas.Rows.Count > 0 Then Dim lstMngDecod As List(Of Manga) = (From dr In dtMangas.AsEnumerable() Select New Manga(Integer.Parse(dr.Item("idmanga")), decode(dr.Item("title").ToString), "", "")).ToList() Dim lstMngFiltered As List(Of Manga) = (From dr In lstMngDecod Where dr.Titulo.ToLower.Contains(filter.ToLower) Select dr).ToList lstMangas.DataSource = lstMngFiltered lstMangas.DisplayMember = "Title" lstMangas.ValueMember = "IdManga" End If End Sub
What I am doing on that code is to show a list of Manganimes I like or know in a ListBox. First of all I use a method written in another class to get the list of mangas I have in the database and I place them in a DataTable.
Then, I build a list of Manga objects (which I have designed in another class) helped with LINQ and I decode the titles while doing so. And finally, I only have to filter that list using LINQ again to build another filtered list, link it with the ListBox and show it.