Reputation: 11
I am sure this is easy (or that I am completely wrong), but all I want to do is get the single values against a LINQ query on a datatable and not use a for.. each loop to access them.
Scenario.. I have a datatable containing a number of rows. I run my query looking for a particular match on "EP" like such..
Dim qryB = From rw In oDT_Cables
Where rw("EP").Equals(br.Position)
Select ld = rw("LOAD"), tl = rw("TOT-LEN")
Now.. I know that I have only one result (due to checking upon insertion), so how do I simply access the items ld and tl without a for each loop??
I have tried:
qryb.elementat(1) error
qryb.elementat(ld) Not possible
qryb.tl not possible
Does anyone know how I can access tl and ld from the query please? It is much appreciated.
Brett
Upvotes: 0
Views: 104
Reputation: 54427
If you know for a fact that a LINQ query produces a single result then you call Single
.
Dim result = qryB.Single()
If there may be no result but will never be more than one then you call SingleOrDefault
and the result may be Nothing
. If there will be at least one result but may be more and you want just the first, you call First
. If there may be zero, one or more and you want the first if there is one then you call FirstOrDefault
and the result may be Nothing
.
Note that some LINQ providers don't support both options, e.g. LINQ to Entities (the LINQ provider for Entity Framework) supports First
and FirstOrDefault
but not Single
or SingleOrDefault
(unless it's changed recently) while, if I'm not mistaken, LINQ to SQL supports Single
and SingleOrDefault
but not First
or FirstOrDefault
.
Note that, if you were going to use ElementAt
, you would have to specify 0 as the index. ElementAt
works pretty much like indexing a array or other IList
, so the first item is at index 0. You'd only use ElementAt
for something in the middle of a query result though, given that you have Single
, First
and Last
methods and their nullable equivalents.
Upvotes: 1