Solved

LINQ how to return object

Posted on 2010-11-22
6
390 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

707 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now