Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

LINQ how to return object

Posted on 2010-11-22
6
Medium Priority
?
397 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 2000 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

916 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