LINQ: Exception, Null or Object?

I have run into a problem.  LINQ didn’t behave as I had expected when trying to query an object from a list.  So I set out to figure out what I didn’t know.  Turns out I am not alone in this since I have been asked about it several times. This post  will look at what you can expect to happen when you query a list of objects that does not contain the item you are looking for.  This can produce three different outcomes depending on the way you approach it.  You will either get an exception, a null object or an empty object.

Before we begin we need a class to give us some useful data to query against.

I created a real simple Item object with just an id and name, as well as, a simple class to build up a IQueryable<Item> for us to run some LINQ queries against.

   1:      public class Item
   2:      {
   3:          public int Id { get; set; }
   4:   
   5:          public string Name { get; set; }
   6:      }
   7:   
   8:      public class ItemData
   9:      {
  10:          public IQueryable<Item> GetItems()
  11:          {
  12:              var users = new List<Item>
  13:                  {
  14:                      new Item {Id=1, Name = "Item 1"},
  15:                      new Item {Id=2, Name = "Item 2"},
  16:                      new Item {Id=3, Name = "Item 3"},
  17:                      new Item {Id=4, Name = "Item 4"},
  18:                      new Item {Id=5, Name = "Item 5"},
  19:                  };
  20:   
  21:              return users.AsQueryable();
  22:          }
  23:      }

 

Single

var single = items.Single(x => x.Id == 10);

Single returns the single, specific item from a sequence of values that matches your query.  Single throws an exception if there is not exactly one element in the sequence.  In my testing when looking for an item not in the sequence it threw [System.InvalidOperationException] = {"Sequence contains no matching element"}.

Single with DefaultIfEmpty

var singleDefaultIfEmtpy = items.DefaultIfEmpty(new Item()).Single(x => x.Id == 10);

So what changes of we add the .DefaultIfEmpty(new Item()) to the query?  None at all, it still throws [System.InvalidOperationException] = {"Sequence contains no matching element"}.

SingleOrDefault

 
var singleOrDefault = items.SingleOrDefault(x => x.Id == 10);

This one is a little better, it doesn’t throw an exception it returns null.  Why didn’t it return an empty Item object?  You’d think that would be the default and that it could figure it out because it knows what type of object we are querying for.  Nope, if you don’t specify the default value you get null.

SingleOrDefault with DefaultIfEmpty

Ok, so lets specify a default value with .DefaultIfEmpty.

var singleOrDefaultIfEmpty = items.DefaultIfEmpty(new Item())
                .SingleOrDefault(x => x.Id == 10);

I expected to get a new Item object, but guess what I got null.  I couldn’t figure out why, the documentation states ‘The SingleOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource), use the DefaultIfEmpty(Of TSource)(IEnumerable(Of TSource), TSource) method as described in the Example section.’

I did that yet I still got a null, and not an empty Item object.  Hopefully, you guys can tell me why.

First and FirstOrDefault, Last and LastOrDefault

First, FirstOrDefault and Last and LastOrDefault gave the same results as their respective counterparts.  It appears that the OrDefault doesn’t mean anything.

Where

Let’s look at using Where(), cause hey let’s be honest this is the way I write most of my queries anyway.  Where by itself returns IQueryable<T> which what we expect, but let’s look at what happens when use DefaultIfEmpty by itself and with First and FirstOrDefault.

Where with DefaultIfEmpty

var whereDefaultIfEmpty = items.Where(x => x.Id == 10)
                .DefaultIfEmpty(new Item());
 

Hey, we are finally starting to get some results, this returned a new Item object.

Where with First

Ok, so what if we put First?

var whereFirst = items.Where(x => x.Id == 10).First();

Oh, here is our old friend InvalidOperationException, no joy!

Where with First and DefaultIfEmpty

So, for fun let’s see if adding the DefaultIfEmpty makes a difference.
 
var whereFirstDefaultIfEmpty = items.Where(x => x.Id == 10)
                .DefaultIfEmpty(new Item())
                .First();
 

This return a new Item object. Ok, so now we are starting to see when DefaulIfEmpty helps. Remember just using it with First without Where just threw an exception.

Where with FirstOrDefault

var whereFirstOrDefault = items.Where(x => x.Id == 10).FirstOrDefault();
 

This behaved no different than just using FirstOrDefaul(x=> x.Id == 10), we got a null.

Where with FirstOrDefault and DefaultIfEmpty

Ok, so DefaultIfEmpty made a difference when using First, let’s hope it does the same for FirstOrDefault.

var whereFirstOrDefaultIfEmpty = items.Where(x => x.Id == 10)
                .DefaultIfEmpty(new Item())
                .FirstOrDefault();

Eureka! A new Item object.

Summary

From what I was able to figure out reading the online documentation and my own testing it I recommend using DefaultIfEmpty() with Where() alone or with FirstOrDefault.  But remember using it with Single, SingleOrDefault, First, FirstOrDefault, Last, or LastOrDeafult will not get you the default object, you will either get an InvalidOperationException or  null.

Now that I understand how and when DefaultIfEmpty makes a difference I can create LINQ queries that return the results I expect and I will be able to predict if I will get an Exception, Null or Object.

If you have experienced something different, disagree, or have a better way to approach this please post a reply.  The discussion just makes all of us better.

Definitions of Designations

Saw this on Google+ posted by Eric Miao and just had to share it.  I am not sure where he got it but it sure made me laugh.

Definitions of Designations

  • Project Manager is a Person who thinks nine women can deliver a baby in One month.
  • Developer is a Person who thinks it will take 18 months to deliver a Baby.
  • Onsite Coordinator is one who thinks single women can deliver nine babies in one month
  • Client is the one who doesn’t know why he wants a baby.
  • Marketing Manager is a person who thinks he can deliver a baby even if no man or woman are available
  • Resource Optimization Team thinks they don’t need a man or woman; they’ll produce a child with zero resources
  • Documentation Team thinks they don’t care whether the child is delivered, they’ll just document 9 months
  • Quality Auditor is the person who is never happy with the PROCESS to produce a baby
  • Tester is a person who always tells his wife that this is not the Right baby
  • HR Manager is a person who thinks that a donkey can deliver a human baby in given 9 months

First WP7 Application: Dominionizer

image

Dominionzier

Over that last several months Chris Koenig and myself have been working on a Windows Phone 7 application that helps ease the task the picking the kingdom cards for playing the game of Dominion.  Version 1.0 to the market place and received certification in 3 days and it went live over the weekend.

It has been an awesome project to work on and we have a few features we want to add in version 2.0.  Currently supported cards sets: Dominion, Intrigue, Seaside, Alchemy, Prosperity, and Cornucopia, as well as the three promo cards.

I want to thank Chris for all of his support and patience while working with me on the project.  If you are a fan of Dominion please check out.

Description from Windows Phone Market Place

Dominionizer is an application to help ease the task of picking the 10 kingdom cards needed to play the card game Dominion.

Diminionizer supports the following Dominion, Intrigue, Seaside, Alchemy, Prosperity, and Cornucopia, as well as the three promo cards.

Settings allow you to control which sets are included in random selection. Other options allow you to apply rules to how the cards are picked, current rules allow for Require 2-5 Cost Cards and Require Reaction To Attack.

Once the cards are picked you may swap a card out for a different randomly selected card by tap-hold and selecting Swap Card. If you can't remember what a card does you can also tap-hold and select View Card to see the card information.

Screenshots

Dominionizer_Main Dominionizer_Main_Menu

The main screen displays the randomly picked cards along with cost, potion cost, and an icon to indicate which set the cards came from.  If you do not like a card you can use the hold menu to swap the card for a different card, or view an image of the actual card.

Dominionizer_Settings Dominionizer_Rules 

Settings allow you to control which sets are used for the card selection, and rules allow you to control how the cards are picked.  If you want to make sure you have an even spread of cost you can turn on the Require Two to Five Cost Cards rule.  If you don’t want to have an attack card without a way to defend yourself turn on the Require Reaction To Attack rule.

Microsoft MVP: ASP.NET/IIS Awarded; Again!

image

Microsoft once again has chosen to award me with the MVP Award for ASP.NET/IIS.  Once again I find myself very honored and humbled to be recognized for my efforts in the community.  I have always said that even if I am not an MVP I will continue to go out and foster community wherever I can, and I will, but not just yet.

I want to thank the Northwest Arkansas Technical community, hey they have to put up with me Winking smile.  They have been a great source of ideas and inspiration and I would go to bat for any of you.  Thanks for listening to me rant, and for sometimes telling me to shut up Smile.

Thanks again to Microsoft for the honor of being an MVP and thanks to the community for helping me get there.

Introduction to Agile Software Development Video on UserGroup.tv

The video recording of my presentation: Introduction to Agile Software Development at the Tulsa School of Dev has been posted on User Group TV website. 

Thanks to Shawn Weisfeld for all the time and money he has put into finding a way to bring community event to a broader audience.

Calendar

<<  November 2014  >>
MonTueWedThuFriSatSun
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar

Month List