SoFunction
Updated on 2025-03-01

Operation of using the First method to get the first element in C#

During the C# List collection operation, if you want to obtain the first element object in the List collection, you will generally first get the first element by obtaining the list[0].

In fact, the First() method to get the last element is provided in the List collection. Calling this method can directly obtain the first element in the List collection.

For example, there is an object list1 of the List<int> collection. If you want to obtain the first element of the object in the collection, you can use the First() method, as follows:

List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var firstInt=();

Supplementary knowledge:Use First, Last, Single methods in the List collection

Operator

If the source sequence is empty

The source sequence contains only one element

The source sequence contains multiple elements

First

Throw an exception

Return this element

Return the first element

FirstOrDefault

Return default(TSource)

Return this element

Return the first element

Last

Throw an exception

Return this element

Return the last element

LastOrDefault

Return default(TSource)

Return this element

Return the last element

Single

Throw an exception

Return this element

Throw an exception

SingleOrDefault

Return default(TSource)

Return this element

Throw an exception

It is obvious that if the input sequence has only one element, the execution results of these operators are very consistent :) Similarly, if the input sequence is empty, the operator without "OrDefault" will throw an exception (InvalidOperationException), while the operator with "OrDefault" will return the default value of the element type (the default value of the reference type is null, the default value of int is 0, etc.).

If the (probably filtered) input sequence contains multiple elements, the execution results of these operators vary greatly. The results of First and Last are as the name suggests, while Single throws an exception.

It is worth noting that SingleOrDefault will also throw an exception because it does not do something like this: if there is only one element in the input sequence, it will return that element, otherwise it will return the default value.

If you need an operator that can handle multi-element sequences, use First or Last. If you need to handle sequences that may be empty, use FirstOrDefault or LastOrDefault. Note that if an operator with "OrDefault" is used, the execution result of an empty sequence and a sequence containing only default values ​​will be exactly the same.

The above article in C# is the operation of using the First() method to obtain the first element in List collection in C#. It is all the content I share with you. I hope you can give you a reference and I hope you can support me more.