dinotom
dinotom

Reputation: 5162

differences in LINQ queries

Can someone explain why, when a query should be returning one string item only like in the example below;

From c in context.Products Where c.Id=prodId Select c.Name

Why cant that be done like so;

Dim prodDeleted as String = (From c in context.Products Where c.Id=prodId Select c.Name).ToString()

bvecause it returns this (System.Data.Objects.ObjectQuery`1[System.String]) , instead of the product name

versus having to do it like so;

 Dim prodDeleted = (From c In ctx.products
                               Where c.Id = prodId
                               Select c).FirstOrDefault()

 Dim deletedprodname As String = prodDeleted.Name.ToString()

Upvotes: 2

Views: 44

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245389

Because all calls to Select return an IEnumerable rather than a single element.

To verify that your query really returns a single element, you need to add the call to Single. Or, if you don't care if a single element or multiple elements were returned, you can grab the first using First.

If you're not against using the VB.NET equivalent of lambda syntax, you can streamline everything:

Dim deletedProdName As String = 
    ctx.products.SingleOrDefault(Function(c) c.Id = prodId).Name

Upvotes: 2

Related Questions