In this article we will learn, how to Single () method in LINQ or what is Single() method in LINQ C# MVC with example.


In LINQ, Single method is used to return single element form collection in case if there are no elements present in the collection/List or  returns more than one element then it will throw "InvalidOperationException" error.

Example of LINQ SingleOrDefault() Method

Following is the example of LINQ Single method to get single element from collection or default value in case if collection contains no elements.


using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace SQLTutorialsPoint
    class Employee
        public string Name { get; set; }
        public int ID { get; set; }
    class Program
        static void Main(string[] args)
            List<Employee> Employee = new List<Employee>(){
            new Employee() {  Name = "Suraj",ID  = 1},
            new Employee() {  Name = " Suraj ", ID=  2 },
              new Employee() {  Name = "Sumit", ID=  3 },
            new Employee() {  Name = "Pankaj", ID = 4},
            new Employee() {  Name = "Rahul", ID = 5}}.ToList();
            var result = Employee.Single(i => i.Name == "Suraj");
            Console.WriteLine(" ID:" + result.ID + "Name:" + result.Name);


As you see above example it will throw "InvalidOperationException" error because Single() method will get multiple elements as result.

Now we will run and see the output.

 use of single method in linq

In this article we learned, how we can use LINQ Single() method in c# to show default value in case if the list or collection returns null or empty value then throw “InvalidOperationException” error.


I hope it will help to you after reading.



Leave a comment

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

You may also like