Solved

LINQ how to return object

Posted on 2010-11-22
6
394 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 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
Industry Leaders: 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!

 

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

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video Micro Tutorial shows how to password-protect PDF files with free software. Many software products can do this, such as Adobe Acrobat (but not Adobe Reader), Nuance PaperPort, and Nuance Power PDF, but they are not free products. This vide…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

729 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