What is difference between First and FirstOrDefault in LINQ?

Last week I were presenting LINQ to group of almost 100 audience. While writing query a question raised that what is difference between First and FirstOrDefault . At that time I was not very sure about answer so I asked audience to help me. One from audience answered this question. So credit of this blog to him. For benefit of all I am documenting answer below,

Let us focus on answer of this question. I am sure that you may have come across following query in LINQ.

In below query we are fetching First record on given condition.

image

Now there are two kind of result you can expect.

  • Either a product on basis of criteria
  • Or there is no product on given criteria

If there is no product on the critera you are searching then LINQ will throw you run time exception of type InvalidOperationException

image

So when you are working with First() make sure that you have handled the InvalidOperationException else you may encounter exception if there is no result matched on given criteria. So you may want to modify code as given below,

try
 {
 Product result = (from r in GetProducts()
 where
 r.ProductId == 1
 select r).First();
 }
 catch (InvalidOperationException ex)
 {
 Console.WriteLine(ex.Message);
 }

If there is no match then you will get output as below,

clip_image002

Next option is FirstOrDefault . So you may have come across following query. If there is no Product matched on given criteria then LINQ will return NULL.

image

So assume there is not matched Product and query has returned NULL then in that case if you access result then you will get exception as following

image

To avoid run time NullReferenceException you can modify code as following,

Product result1 = (from r in GetProducts()
 where
 r.ProductId == 1
 select r).FirstOrDefault() ;
 if (result1 != null)
 {
 Console.WriteLine(result1.ProductPrice);
 }

else
 {
 Console.WriteLine("No Record Found");
 }

 

Now when there is no Product code will gracefully print a message that No Record Found. This is basic difference between First and FirstOrDefualt. I hope you find this post useful. Thanks for reading.

Organised and Presented at June meeting of C-Sharp Corner Delhi Chapter

Yes we done that. It was third event in row (April, May, June) when we organised C-Sharp Corner Delhi Chapter Meet with more than 100 attendees. We did June month meeting on 22nd June in Noida and once again we had more than 100 audience.

Read official recap here

Join Chapter here

We followed following agenda. Suchit Khanna and Brij Mishra was impeccable as speaker. Big thanks to core members Pravin Kumar, Dinesh beniwal and Amlendu Dey for their unconditional support.

image

 

We started day with LINQ. This session lasted for around 2 Hrs. I discussed in detail about LINQ to audience. I touched upon following topics,

  1. LINQ to Object
  2. Implicit Type Local variable
  3. Object Initializer
  4. Collection Initializer
  5. LINQ to SQL
  6. Executing SP and SQL Query in LINQ
  7. Remote and Local execution in LINQ
  8. Logging in LINQ
  9. CRUD operation in LINQ
  10. Conflict resolution in LINQ

 

image

 

After my session Brij discussed about ASP.NET MVC and then further Suchit Khanna enlightened audience with ASP.NET Web API.

You can see happy faces at end of event.

 

image

 

Our next event is on 20th July. If you want to be member of the chapter then feel free to join here

TestFixtureSetUp and TestFixtureTearDown in Unit Testing using NUnit: Part 4

We have been learning Unit Testing using NUnit together. Read first three parts of this series below,

How to do Unit Test using NUnit : Part 1

Test SetUp and TearDown in Unit Testing using NUnit : Part 2

Ignore Test in Unit Testing using NUnit: Part 3

In Part 2 , we discussed about TestSetUp and TearDown. If notice TestSetUP and TearDown is related to tests. They both get executed each time a test get executed. So if there are 5 tests in Test Fixture then TestSetUp and TearDown will get executed 5 times. Sometime this is good and needed for certain requirements. However doing heavy tasks like cleaning up whole database etc. each time for a test may not be a good idea. You may want to perform certain task for whole test fixture than for each and individual tests.

You can execute certain code before execution of all the tests in test fixture by using attributing that code with [TestFixtureSetUp]. This is used to create setup for all tests at one instant.

So you can create TestFixtureSetup or setup for whole test as following,

clip_image002

Basically we use TestFixtureSetUp to setup for all test. On the other hand you can clean up for all tests once using TestFixtureTearDown.

clip_image004

Using TestFixtureSetUp and TestFixtureTearDown are used to set up test and clean up test. I hope you find this post useful. Thanks for reading.

Ignore Test in Unit Testing using NUnit: Part 3

We have been learning Unit Testing using NUnit together. Read first two part of this series below,

How to do Unit Test using NUnit : Part 1

Test SetUp and TearDown in Unit Testing using NUnit : Part 2

You may come across a scenario when test is itself broken. While executing test you need to ignore certain broken kind of test. Thankfully NUnit provides a very simple solution to ignore a test. By using ignore attribute you can ignore a test.

clip_image002

You can ignore a unit test as following

clip_image004

Let us go back to unit test we wrote in previous part of this series and modify test as following,


[Test]
 [Ignore("Ignore this test it is broken")]
 public void IsValidProductPrice()
 {

 p.ProductPrice = 100;
 if (p.ProductPrice > 0)
 {
 result = true;
 }

Assert.IsTrue(result, "Product Price is valid");

 }

On execution of test you will find that Test Runner has ignored this test. Test runner will skip test attributed with ignore.

clip_image002[6]

In this post we learnt how easily a test can be ignored in NUnit. I hope you find this post useful. Thanks for reading.

Test SetUp and TearDown in Unit Testing using NUnit : Part 2

Read Part 1 here: How to do Unit Test using NUnit : Part 1

In last post we talked about how to start with Unit Testing using NUnit. In this post I will discuss about following two topics,

  1. Test Setup
  2. Test Teardown

You need Test Setup and Test Teardown to remove any dependency between tests. Assume a scenario that

  • You want to create instance of a particular object before execution of any test
  • You want to delete a particular file from file system before execution of any test
  • You want to insert some test data or create some test data before execution of any test etc..

In above stated scenario you may want to create a Test Setup. Test Setup is a piece of code get executed before execution of any test.

clip_image002

Other use case could be that you want to perform a particular task after execution of each test. So once test got executed a certain task should get done and we call that Test Teardown. There could be scenario that

  • You want to destruct an instance after execution of any test
  • You want to remove test data after execution of any test
  • You want to delete a file from file system after execution of any test etc.

In above scenario you may want to create Test Teardown. Test Teardown is piece of code get executed after execution of any test.

clip_image002[6]

In NUnit you can create Test Setup and Test Teardown by using [Setup] and [TearDown] attribute on a function.

So Test Setup can be created as following,

image

And you can create Test Teardown as following

image

If there are 5 tests in your test class then these two functions will get executed 5 times. Now let us put our discussion into concrete example. Assume that you are writing Unit Test for a Product class. Product class is defined as following,

namespace MyAppToTest
{
 public class Product
 {
 double productPrice;

 public double ProductPrice
 {
 get
 {
 return productPrice;
 }

set
 {
 productPrice = value;
 }
 }
 }
}

A Unit Test is written to test valid product price as following,

[Test]
 public void IsValidProductPrice()
 {

 p.ProductPrice = 100;
 if (p.ProductPrice > 0)
 {
 result = true;
 }

Assert.IsTrue(result, "Product Price is valid");
 }

You can write Test SetUp and TearDown as following,


Product p;
 bool result;
 [SetUp]
 public void TestSetup()
 {
 p = new Product();
 result = false;

 }

[TearDown]
 public void TestTearDown()
 {
 p = null;
 result = false;
 }

The above two function will get executed each time before execution of test and after execution of test. In writing Unit Test , Test SetUp and Test TearDown are very handy and useful. I hope you find this post useful. Thanks for reading.