Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • LINQ - Get Started
  • What is LINQ
  • Why LINQ
  • LINQ API
  • LINQ Query Syntax
  • LINQ Method Syntax
  • Lambda Expression
  • Standard Query Operators
  • Where
  • OfType
  • OrderBy
  • ThenBy
  • GroupBy, ToLookup
  • Join
  • GroupJoin
  • Select
  • All, Any
  • Contains
  • Aggregate
  • Average
  • Count
  • Max
  • Sum
  • ElementAt, ElementAtOrDefault
  • First, FirstOrDefault
  • Last, LastOrDefault
  • Single, SingleOrDefault
  • SequenceEqual
  • Concat
  • DefaultIfEmpty
  • Empty, Range, Repeat
  • Distinct
  • Except
  • Intersect
  • Union
  • Skip, SkipWhile
  • Take, TakeWhile
  • Conversion Operators
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Element Operators: First & FirstOrDefault

The First and FirstOrDefault method returns an element from the zeroth index in the collection i.e. the first element. Also, it returns an element that satisfies the specified condition.

Element OperatorsDescription
FirstReturns the first element of a collection, or the first element that satisfies a condition.
FirstOrDefaultReturns the first element of a collection, or the first element that satisfies a condition. Returns a default value if index is out of range.

First and FirstOrDefault has two overload methods. The first overload method doesn't take any input parameter and returns the first element in the collection. The second overload method takes the lambda expression as predicate delegate to specify a condition and returns the first element that satisfies the specified condition.

First() Á FirstOrDefault() Overloads:
public static TSource First<TSource>(this IEnumerable<TSource> source);public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source);public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

The First method returns the first element of a collection, or the first element that satisfies the specified condition using lambda expression or Func delegate. If a given collection is empty or does not include any element that satisfied the condition then it will throw InvalidOperation exception.

The FirstOrDefault method does the same thing as First method. The only difference is that it returns default value of the data type of a collection if a collection is empty or doesn't find any element that satisfies the condition.

The following example demonstrates First method.

Example: LINQ First() - C#
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
		
Console.WriteLine("1st Element in intList: {0}", intList.First());
Console.WriteLine("1st Even Element in intList: {0}", intList.First(i =&gt; i % 2 == 0));

Console.WriteLine("1st Element in strList: {0}", strList.First());

Console.WriteLine("emptyList.First() throws an InvalidOperationException");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(emptyList.First());
Try it
Output:
1st Element in intList: 7
1st Even Element in intList: 10
1st Element in strList:
emptyList.First() throws an InvalidOperationException
-------------------------------------------------------------
Run-time exception: Sequence contains no elements...

The following example demonstrates FirstOrDefault method.

Example: LINQ FirstOrDefault() - C#
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
		
Console.WriteLine("1st Element in intList: {0}", intList.FirstOrDefault());
Console.WriteLine("1st Even Element in intList: {0}",
                                 intList.FirstOrDefault(i =&gt; i % 2 == 0));

Console.WriteLine("1st Element in strList: {0}", strList.FirstOrDefault());

Console.WriteLine("1st Element in emptyList: {0}", emptyList.FirstOrDefault());
Try it
Output:
1st Element in intList: 7
1st Even Element in intList: 10
1st Element in strList:
1st Element in emptyList:

Be careful while specifying condition in First or FirstOrDefault. First will throw an exception if a collection does not include any element that satisfies the specified condition or includes null element.

If a collection includes null element then FirstOrDefault throws an exception while evaluting the specified condition. The following example demonstrates this.

Example: LINQ First() & FirstOrDefault() - C#
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
		
Console.WriteLine("1st Element which is greater than 250 in intList: {0}", 
                                intList.First( i > 250));

Console.WriteLine("1st Even Element in intList: {0}", 
                                strList.FirstOrDefault(s =&gt; s.Contains("T")));
Try it
Output:
Run-time exception: Sequence contains no matching element
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.