Hi guys i want to return one element if my list empty or null

This is employee list:

class Employee
        public string Name { get; set; }
        public int ID { get; set; }

My Employee  List:

List<Employee> Employee = new List<Employee>();


  Please help me.

1 Answers

  1. Aditya Kumar Patel
    Re:how to return a single element using defaultifempty in linq c# priyanka patel
    10/8/2018 5:40:48 PM

    The DefaultIfEmpty() method returns a new collection with the default value if the given collection on which DefaultIfEmpty() is invoked is empty.

    Try to use it:


    var Emp = from output in Employee.DefaultIfEmpty() 
                            select new { Name = "Aditya", ID = "1001" };
                foreach (var item in Emp)
                    Console.WriteLine(" ID:" + item.ID +" Name:"+item.Name);               

    I hope it will help to you.

Leave a answer

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like