LINQ: Inserting into a new type

What i like about LINQ is that you can avoid iterating, thereby making your codes shorter and, well, more elegant.

Let’s try this one: I have my type right here

Public Class App

    Public Property ID As String

    Public Property Description As String

End Class

What i can do is to create my command, and iterate through it, creating an object one after the other

Dim myApps As New List(Of App)

For Each dataRowHere As DataRow In dtApps.Rows

     Dim newApp As New App()

     newApp.ID = dataRowHere("ID")

     newApp.Description = dataRowHere("Descp")

     myApps.Add(newApp)

Next

Of course, that will work. But we can also do it this way

Dim _myEntities = New MyEntities()

Dim _appList As ObjectQuery(Of App) = From queryHere In _wflAuthEntities.WFL_APP

            Select New App With {.ID = queryHere.ID,

                                .Description = queryHere.DESCP}

Return _appList

I just create an ObjectQuery of type App, and directly instantiate a new object from my query. You can also set your filter here by adding a WHERE. But you already know that.

Also coming from IEnumerable (obviously), you can use this as a Datasource for your UI.

ddlApps.DataValueField = "ID"

ddlApps.DataTextField = "Description"

ddlApps.DataSource = AuthDA.GetAppNames()

ddlApps.DataBind()

I’m a bigger fan of C# rather than VB. I’m just using this more often nowadays.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s