Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post


First() :

I will prefer using First() when I am confident about collection or sequence that it contains at least one element.


I will prefer FirstOrDefault() when I don’t know whether collection or sequence contains element, FirstOrDefault() handles null or empty sequence by itself that is main difference.

Code example:

var Dptms = (from d in BlogDbContext.Department
             join u in BlogDbContext.User
             on new { PID = d.CreatedBy } equals new { PID = u.UserId }
                        select new
                              DepartmentId = d.DepartmentId,
                              DeptName = d.DeptName,
                              Description = d.Description,
                             CreatedBy = u.UserName
//First() extension method
if (Dptms.Any())
   { var FirstDeprtment =Dptms.First();
//FirstOrDefault() extension method
var FirstDept = Dptms.FirstOrDefault();

Share your answer

Share as a guest

Please subscribe me to the CodeChef4U.

By creating your new answer, you agree to the privacy policy and terms of service.