Introduction:

 

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

Description:

In LINQ, First() method is used to return first element from the list / collection In case if there no elements present in list / collection based on specified condition then LINQ First() method will throw “InvalidOperationException” error

Example of LINQ First() Method

Following is the example of using LINQ First() method to return first element from the list in case if no elements present in the list throw “InvalidOperationException” error.

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 = "pawan", ID  = 1},
            new Employee() {  Name = "Rajeev", ID =  2 },
              new Employee() {  Name = "Sumit", ID =  3 },
            new Employee() {  Name = "Pankaj", ID = 4 },
            new Employee() {  Name = "Rahul", ID = 5}}.ToList();
 
        var result = Employee.First(i => i.Name== "pawan");
            Console.WriteLine("--------Employee----------");
            Console.WriteLine(" ID:" + result.ID + " Name:" + result.Name);
            Console.ReadLine();
        }
    }
}

 

As you see above example we are getting first element from “employee” collection object by using LINQ First() method.


Now we will run and see the output.

 LINQ First() method in c#


In this article we learned, how we can use LINQ First() method  to get first element from the list in case if no elements present in the list throw “InvalidOperationException” error.

 

I hope it will help to you after reading.

comments


Leave a comment

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

You may also like