Solved

LINQ how to return object

Posted on 2010-11-22
6
393 Views
Last Modified: 2012-05-10
How do I get a LINQ query to return just a single object instead of a collection? Say I query a collection of 100 items and I only want the search to return 1 object. How do I get LINQ to return just the object, rather than a collection with a single object?
0
Comment
Question by:ShaunDumas
  • 3
  • 2
6 Comments
 
LVL 32

Expert Comment

by:Erick37
ID: 34191726
You can get the "Top 1" with Take(1)

Dim items = (From item In foo Select New With {.NewItem = item}).Take(1)
0
 

Author Comment

by:ShaunDumas
ID: 34191750
Nice :)

That gives me just the top one, perfect. Can I then get it to return just the object and not the collection?

e.g. get "item" back instead of "items", or is there a better way?
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 500 total points
ID: 34191758
Take is good for returning a list of a specified number of objects, if you just want the first result you can use .First or .FirstOrDefault (both methods work, .FirstOrDefault just kinda makes more sense to me, i.e. no sense in having a list of objects if you know you're only ever gonna have one).

I used a string as an example, but you could just replace string with whatever object you wanted.
Module Module1

    Sub Main()
        Dim strings As String() = {"One", "Two", "Three", "Four"}
        Dim result As String = (From s In strings
                               Where s.Length > 3
                               Select s).FirstOrDefault()
        If IsNothing(result) Then
            Console.WriteLine("No Strings Found")
        Else
            Console.WriteLine("First string longer than three chars: {0}", result)
        End If

        Console.ReadKey()
    End Sub

End Module

Open in new window

0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 

Author Closing Comment

by:ShaunDumas
ID: 34192121
Beautiful, thank you!
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 34192196
I should have pointed out that .FirstOrDefault() will return whatever the default value is for the type you're querying if there are no matching results - for a string or reference-type object that default would be null, so you can easily use IsNothing to check that the query didn't find zero matches.

However, if you're querying a value-type (like an array of Integers), and there are no matches, FirstOrDefault() will return the default value for an Integer, which is 0; and you may not be able to determine the difference between a default or the first item in the result set.  In this case you can use .First() instead, which will throw an exception if there are no matching values.
Module Module1

    Sub Main()
        Dim ints As Integer() = {0, 1, 2, 3, 4}

        Dim firstOverFive = (From n In ints
                             Where n > 5
                             Select n).FirstOrDefault()
        'This would incorrectly show the first value larger than 5 as 0
        Console.WriteLine("The first value over 5 is: {0}", firstOverFive)


        Dim noRecordsReturned As Boolean = False
        Try
            firstOverFive = (From n In ints
                             Where n > 5
                             Select n).First()
        Catch ex As InvalidOperationException
            noRecordsReturned = True
        End Try
        If noRecordsReturned Then
            Console.WriteLine("No Values Larger Than 5 Found")
        Else
            Console.WriteLine("The first value over 5 is: {0}", firstOverFive)
        End If

        Console.ReadKey()
    End Sub

End Module

Open in new window

0
 

Author Comment

by:ShaunDumas
ID: 34200584
Ahh, that is very good to know!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question