Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

LINQ how to return object

Posted on 2010-11-22
6
Medium Priority
?
396 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

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.

Question has a verified solution.

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

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

715 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