Sunday 11 February 2018

Difference between First() and FirstOrDefault() in C#.

In this article, We will discuss about What is the difference between First() and FirstOrDefault() in C#.

First()
---------
- First method Returns the First element of a sequence.
- Generates Error If it does not contain any element.

Example:
------------
public ActionResult Index()
        {
            SampleEntities obj = new SampleEntities();

            int Id = 2;

            var memList = (from x in obj.Memberships where x.ID == Id select x).First();

            return View();
        }

In the above Code, We use Index Action method and used First() and When Id=2 match with database then it will return the result otherwise it Will generate the Error and Which is Shown in below figure,

FirstOrDefault()
--------------------
- FirstOrDefault method Returns the First element of a sequence, or a default value if the Sequence contains no elements. 
- Returns null if it does not contain any element.

Example:-

-------------
public ActionResult Index()
        {
            SampleEntities obj = new SampleEntities();

            int Id = 2;

            var memList = (from x in obj.Memberships where x.ID == Id select x).FirstOrDefault();

            return View();
        }

In the above Code, We use Index Action method and used FirstOrDefault() and When Id=2 match with database then it will return the result otherwise it Will return null and Which is Shown in below figure,

0 comments:

Post a Comment