In LINQ, the First() method/operator returns the first element from the sequence of items in the list/collection or the first element in the sequence of items in the list based on the specified condition. In case if there are no elements present in the list/collection based on specified conditions, then LINQ First() method will throw an error.
Syntax of LINQ First() Method
Following is the syntax of using the LINQ First() method to get the first element from the list.
LINQ First() Method Syntax in C#
int result = objList.First();
LINQ First() Method Syntax in VB.NET
Dim result As Integer = objList.First()
If you observe the above syntax, we are getting the first element from the “objList” collection using LINQ First() method.
LINQ First() in Method Syntax Example
Following is the example of using the LINQ First() operator in method syntax to get the first element from the collection.
C# Code
using System;
using System.Linq;
namespace LINQExamples
{
class Program
{
static void Main(string[] args)
{
int[] objList = { 1, 2, 3, 4, 5 };
int result = objList.First();
Console.WriteLine("Element from the List: {0}", result);
Console.ReadLine();
}
}
}
VB.NET Code
Module Module1
Sub Main()
Dim objList As Integer() = {1, 2, 3, 4, 5}
Dim result As Integer = objList.First()
Console.WriteLine("Element from the List: {0}", result)
Console.ReadLine()
End Sub
End Module
If you observe the above example, we get the first element from the “objList” collection object by using the LINQ First() operator in method syntax.
Result of LINQ First() in Method Syntax Example
Following is the result of the LINQ First() operator in the method syntax example.
First Element from the List 1
LINQ First() in Query Syntax Example
Following is the example of using the LINQ First() operator in query syntax to get the first element from the list.
C# Code
using System;
using System.Linq;
namespace LINQExamples
{
class Program
{
static void Main(string[] args)
{
int[] objList = { 1, 2, 3, 4, 5 };
int result = (from l in objList select l).First();
Console.WriteLine("Element from the List: {0}", result);
Console.ReadLine();
}
}
}
VB.NET Code
Module Module1
Sub Main()
Dim objList As Integer() = {1, 2, 3, 4, 5}
Dim result As Integer = (From l In objList).First()
Console.WriteLine("Element from the List: {0}", result)
Console.ReadLine()
End Sub
End Module
Result of LINQ First() in Query Syntax Example
Following is the result of the LINQ First() operator in query syntax example.
Element from the List: 1
This is how we can use LINQ First() in method syntax and query syntax to get the first element from the list/collection in c#, vb.net.