none
Testing for no results from a query in LINQ RRS feed

  • Question

  • After executing the following code in LINQ, how do I perform a test to see if the selection is empty?

                    Dim myResult = (From x In db.table _
                                 Where x.id = _Id.ToString _
                                 Select x).Single

    'Perform test here for records returned
    Sunday, May 17, 2009 3:30 PM

Answers

  • As far as I understand the Single method, it will throw an InvalidOperationException if the result is not a sequence of exactly one item. Thus with an empty selection you would get an exception on the Single call and you would need to catch that.
    If you don't want the exception then use

    Dim myResult = (From x In db.table _
                                 Where x.id = _Id.ToString _
                                 Select x).SingleOrDefault()

    instead, then you can check

    If myResult Is Nothing Then ...

    to find out whether the selection was empty.

    MVP XML My blog
    Sunday, May 17, 2009 4:07 PM

All replies

  • As far as I understand the Single method, it will throw an InvalidOperationException if the result is not a sequence of exactly one item. Thus with an empty selection you would get an exception on the Single call and you would need to catch that.
    If you don't want the exception then use

    Dim myResult = (From x In db.table _
                                 Where x.id = _Id.ToString _
                                 Select x).SingleOrDefault()

    instead, then you can check

    If myResult Is Nothing Then ...

    to find out whether the selection was empty.

    MVP XML My blog
    Sunday, May 17, 2009 4:07 PM
  • Thanks! I will give that a try. It is a shame that Microsoft's examples don't show something as simple and necessary as this.
    Sunday, May 17, 2009 7:47 PM
  • Which examples did you find? Were the MSDN documents insufficient here? http://msdn.microsoft.com/en-us/library/bb156472.aspx and http://msdn.microsoft.com/en-us/library/bb359429.aspx

    Monday, May 18, 2009 12:17 AM
    Answerer
  • Is this code helpful ?

    var results =
    	from	a in dctx.GetTable<A>()
    	where	(a.IdA == id_a)
    	select a;
    
    // ***** check results *****
    if (results.Count() == 0)
    	throw new UnknownAException("unknown A with specified ID");
    
    if (results.Count() > 1)
    	throw new MultipleAException("multiple A with specified ID");
    
    return (A)results.Single();
    
    
    Monday, May 18, 2009 9:39 AM