Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8379439
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T16:11:11+00:00 2026-06-09T16:11:11+00:00

Quite often I find myself writing code like this: Dim oRenewalOrder = (From c

  • 0

Quite often I find myself writing code like this:

Dim oRenewalOrder = (From c in dc.Orders _
                     Where c.CustomerID = iCustomerID _
                     And c.Type = "RENEWAL").FirstOrDefault()

If oRenewalOrder Is Nothing Then
   Throw New Exception("Can't find renewal order for customer " & iCustomerID) ' or assert, if you prefer
End If

' Continue processing...

I would prefer to use the First() method instead, since it already throws an exception when there is no element. But that exception tells you nothing about what caused it, making it harder to debug. So I want to write a FirstOrException() extension method that I can use like this:

Dim oRenewalOrder = (From c in dc.Orders _
                     Where c.CustomerID = iCustomerID _
                     And c.Type = "RENEWAL").FirstOrException("Can't find renewal order for customer " & iCustomerID)

' Continue processing...

The problem is that it’s hard to write such a method in a generic way, to work with both LINQ to Objects and take advantage of the query optimizations present LINQ to SQL. The best I can come up with is this:

    ''' <summary>
    ''' Returns the first element of a sequence.
    ''' If the sequence is empty, an InvalidOperationException is thrown with the specified message.
    <Extension()> _
    Function FirstOrException(Of T)(ieThis As IEnumerable(Of T), sMessage As String) As T
        Try
            Return ieThis.First()
        Catch ex As InvalidOperationException
            Throw New InvalidOperationException(sMessage, ex)
        End Try
    End Function

I also wrote another equivalent extension method for IEnumerable(Of T), to cover the LINQ to Objects case. These work well, but it seems bad to have to catch an exception and rethrow it. I tried a different approach, using Take(1) and AsEnumerable(), but when I profiled it, it was running two separate SELECT TOP 1 statements:

    <Extension()> _
    Function FirstOrException(Of T)(iqThis As IQueryable(Of T), sMessage As String) As T
        Dim aFirst = iqThis.Take(1).AsEnumerable()
        If aFirst.Count() <= 0 Then
            Throw New InvalidOperationException(sMessage)
        Else
            Return aFirst(0)
        End If
    End Function

So I’m back to the exception handling method. I don’t like it because there is a possibility that whatever LINQ provider is underlying the collection will throw an InvalidOperationException when there is a different problem — not a lack of results, but something else. This would cause my code to mistakenly think there were no results, when in fact it was a different problem entirely.

…

Well, as so often happens when you type up a detailed question, I think I found a better solution, and I will post it in the answers below. But I’ll leave the question open in case anyone finds something better 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T16:11:13+00:00Added an answer on June 9, 2026 at 4:11 pm

    I found that Take(1).ToArray() is the cleanest solution. It causes only a single query to be sent to the database. Note that in the code below I am doing separate extension methods for IEnumerable and IQueryable to support both LINQ to SQL and LINQ to Objects.

        ''' <summary>
        ''' Returns the first element of a sequence.
        ''' If the sequence is empty, an InvalidOperationException is thrown with the specified message.
        <Extension()> _
        Function FirstOrException(Of T)(ieThis As IEnumerable(Of T), sMessage As String) As T
            Dim aFirst = ieThis.Take(1).ToArray()
            If aFirst.Length <= 0 Then
                Throw New InvalidOperationException(sMessage)
            Else
                Return aFirst(0)
            End If
        End Function
    
         ''' <summary>
         ''' Returns the first element of a queryable (e.g. LINQ to SQL) sequence.
         ''' If the sequence is empty, an InvalidOperationException is thrown with the specified message.
        <Extension()> _
        Function FirstOrException(Of T)(iqThis As IQueryable(Of T), sMessage As String) As T
            Dim aFirst = iqThis.Take(1).AsEnumerable()
            If aFirst.Length <= 0 Then
                Throw New InvalidOperationException(sMessage)
            Else
                Return aFirst(0)
            End If
        End Function
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I find myself adding debugging print statements quite often -- stuff like this: print(a_variable_name:
I find myself using the current pattern quite often in my code nowadays var
Aside from the PEAR repository, which I find often has quite messy code with
I find myself with this problem quite often : given a sequence, find the
Case Quite often I find myself staring at some old code that doesn't look
When handling exceptions in python, I find myself repeating code quite often. The basic
I'm currently working on some quite old C++ code and often find things like
Quite often, I find myself wanting a simple, dump object in Python which behaves
I quite often have rows of code like the following: UPDATE my_table SET name
Often when I'm using Python I'll find myself writing list comprehensions that look something

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.