p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   LINQ (http://p2p.wrox.com/linq-280/)
-   -   Retrieving a single value from a single column in a single row? (http://p2p.wrox.com/linq/83678-retrieving-single-value-single-column-single-row.html)

Ron Howerton May 16th, 2011 01:49 PM

Retrieving a single value from a single column in a single row?
 
Is there some simple way to reference a single value from a single column in a single row of a LINQ result set? I don't want to bind it to a control. I don't want to iterate through every row in the set. I just want the equivalent of this:

dim strTemp as string = datatable.row(0)("FieldName")

Imar May 16th, 2011 04:25 PM

Hi Ron,

You can use projection to select only the "column" or property of an object. You can then use FirstOrDefault (or First) to only get a single value. The following code would store Ron in the singleFirstName.FirstName variable:

Code:


Public Class Form1
  Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim list As New List(Of Person) From {New Person() With {.FirstName = "Imar", .LastName = "Spaanjaars"}, New Person() With {.FirstName = "Ron", .LastName = "Howerton"}}
    Dim singleFirstName = (From p In list
                          Where p.LastName = "Howerton"
                          Select New With {.FirstName = p.FirstName}).FirstOrDefault()
  ' singleFirstName.FirstName = Ron
  End Sub
End Class
Public Class Person
  Public Property FirstName As String
  Public Property LastName As String
End Class

This code "projects" the first name property into a new, anonymous object with a single property called FirstName.

You can also assign it to a string variable directly by just selecting the FirstName field, like this:

Code:

Dim singleFirstName = (From p In list
                          Where p.LastName = "Howerton"
                          Select p.FirstName).FirstOrDefault()

If you anticipate multiple results, drop the call to FirstOrDefault and loop over the values in singleFirstName (which then of course has an odd name ;-) ).

Hope this helps,

Imar

Ron Howerton May 17th, 2011 08:46 AM

Right on the first response, as always, Imar! I knew there had to be a simple answer, but all the suggestions I found looked as complex as using SQL Client objects.

Thanks so much!


All times are GMT -4. The time now is 09:56 PM.

Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
2013 John Wiley & Sons, Inc.