DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Default Extension methods

Pranay Rana user avatar by
Pranay Rana
·
Apr. 19, 11 · · News
Like (0)
Save
Tweet
2.44K Views

Join the DZone community and get the full member experience.

Join For Free

In this post I am going to discuss about Default extension method(s) which are use full when we query the data form the collection,array or performing operation while code using linq to sql.

In .net framework there are number of extension methods which allows perform function on the the collection. But problem arise when we don't know the collection or array empty or there is no element after we apply filter.

Methods like .First<t>(),.Last<t>(),.Single<t>() always throws exception InvalidOperationException when object collection is empty or if there is no element available after applying filter condition.

List<int> lstInt = new List<int>(new int[] {15,11,20,30});
var data = lstInt.Single(i => i < 10);

Default Methods
To avoid the exception .net framework has default methods like .FirstOrDefault<t>(),.LastOrDefault<t>(),.SingleOrDefault<t>(), which return the default value if there is no element in the collection or array is empty.

List<int> lstInt = new List<int>(new int[] {15,11,20,30});
var data = lstInt.SingleOrDefualt(i => i < 10);
if (data == 0)
{
   Console.WriteLine("No element found");
}
What if I have collection which is empty and apply the default method, it will return Null value.
class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public static void GetEmployee()
        {
            List<Employee> lstEmp = new List<Employee>();
            var lst = lstEmp.SingleOrDefault();
            if (lst == null)
              Console.WriteLine("list is empty");
        }
}

But I want to display the default value if collection is empty. So for the solution .net Framework provided method DefualtIfEmpty() which allow to do so.
class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public static void GetEmployee()
        {
            List<Employee> lstEmp = new List<Employee();
            Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 };
            var lst = lstEmp.DefaultIfEmpty(defualtEmp).Single();
            
            Console.WriteLine("Employee :" + lst.Name);
        }
}
The above method is also help full when I am apply filter on the collection and collection is empty.
public static void GetEmployee()
{
            List<Employee> lstEmp = new List<Employee>{
                                new Employee(){Name = "Pranay",  Age =25 },
                                new Employee(){Name = "Krunal", Age = 26},
                                new Employee(){Name = "Hanika", Age = 26} 
            };

            Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 };

            var emp = lstEmp.Where(e=>e.Age<20).DefaultIfEmpty(defualtEmp);
            foreach(Employee e in emp)
            Console.WriteLine("Fond Employee: " + e.Name);
}
The above code is the example but it's very help full when I am binding collection with the list controls.

Summary 
The default methods palys important role when we do code with the collection or with the linq to sql or linq to xml and we don't know weather collection is emptry or not. You can get detail information about the methods on msdn.
Filter (software) Framework Element sql Data structure Data (computing) Binding (linguistics) IT

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Memory Debugging and Watch Annotations
  • What SREs Can Learn From the Atlassian Nightmare Outage of 2022
  • How to Leverage Method Chaining To Add Smart Message Routing in Java
  • After COVID, Developers Really Are the New Kingmakers

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo