Queryable.FirstOrDefault Metoda

Definicja

Zwraca pierwszy element sekwencji lub wartość domyślną, jeśli nie znaleziono żadnego elementu.

Przeciążenia

FirstOrDefault<TSource>(IQueryable<TSource>)

Zwraca pierwszy element sekwencji lub wartość domyślną, jeśli sekwencja nie zawiera żadnych elementów.

FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

Zwraca pierwszy element sekwencji, który spełnia określony warunek lub wartość domyślną, jeśli taki element nie zostanie znaleziony.

FirstOrDefault<TSource>(IQueryable<TSource>, TSource)

Zwraca pierwszy element sekwencji lub wartość domyślną, jeśli sekwencja nie zawiera żadnych elementów.

FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>, TSource)

Zwraca pierwszy element sekwencji, który spełnia warunek lub wartość domyślną, jeśli taki element nie zostanie znaleziony.

FirstOrDefault<TSource>(IQueryable<TSource>)

Źródło:
Queryable.cs
Źródło:
Queryable.cs
Źródło:
Queryable.cs

Zwraca pierwszy element sekwencji lub wartość domyślną, jeśli sekwencja nie zawiera żadnych elementów.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source);
public static TSource FirstOrDefault<TSource> (this System.Linq.IQueryable<TSource> source);
public static TSource? FirstOrDefault<TSource> (this System.Linq.IQueryable<TSource> source);
static member FirstOrDefault : System.Linq.IQueryable<'Source> -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource)) As TSource

Parametry typu

TSource

Typ elementów elementu source.

Parametry

source
IQueryable<TSource>

Element IQueryable<T> , aby zwrócić pierwszy element.

Zwraca

TSource

default(TSource) jeśli source jest pusty; w przeciwnym razie pierwszy element w sourcepliku .

Wyjątki

source to null.

Przykłady

Poniższy przykład kodu pokazuje, jak używać w FirstOrDefault<TSource>(IQueryable<TSource>) pustej sekwencji.

// Create an empty array.
int[] numbers = { };
// Get the first item in the array, or else the
// default value for type int (0).
int first = numbers.AsQueryable().FirstOrDefault();

Console.WriteLine(first);

/*
    This code produces the following output:

    0
*/
' Create an empty array.
Dim numbers() As Integer = {}
' Get the first item in the array, or else the 
' default value for type int, which is 0.
Dim first As Integer = numbers.AsQueryable().FirstOrDefault()

MsgBox(first)

' This code produces the following output:

' 0

Czasami wartość nie default(TSource) jest wartością domyślną, której chcesz użyć, jeśli kolekcja nie zawiera żadnych elementów. Zamiast sprawdzać wynik dla niepożądanej wartości domyślnej, a następnie zmienić ją w razie potrzeby, możesz użyć metody , aby określić wartość domyślną, której chcesz użyć DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) , jeśli kolekcja jest pusta. Następnie wywołaj metodę First<TSource>(IQueryable<TSource>) , aby uzyskać pierwszy element. Poniższy przykład kodu używa obu technik w celu uzyskania wartości domyślnej 1, jeśli kolekcja miesięcy liczbowych jest pusta. Ponieważ wartość domyślna liczby całkowitej wynosi 0, która nie odpowiada żadnemu miesiącowi, wartość domyślna musi być określona jako 1. Pierwsza zmienna wynikowa jest sprawdzana pod kątem niepożądanej wartości domyślnej po zakończeniu zapytania. Druga zmienna wynikowa jest uzyskiwana przez wywołanie , DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) aby określić wartość domyślną 1.

List<int> months = new List<int> { };

// Setting the default value to 1 after the query.
int firstMonth1 = months.AsQueryable().FirstOrDefault();
if (firstMonth1 == 0)
{
    firstMonth1 = 1;
}
Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1);

// Setting the default value to 1 by using DefaultIfEmpty() in the query.
int firstMonth2 = months.AsQueryable().DefaultIfEmpty(1).First();
Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2);

/*
 This code produces the following output:

 The value of the firstMonth1 variable is 1
 The value of the firstMonth2 variable is 1
*/
Dim months As New List(Of Integer)(New Integer() {})

' Setting the default value to 1 after the query.
Dim firstMonth1 As Integer = months.AsQueryable().FirstOrDefault()
If firstMonth1 = 0 Then
    firstMonth1 = 1
End If
MsgBox(String.Format("The value of the firstMonth1 variable is {0}", firstMonth1))

' Setting the default value to 1 by using DefaultIfEmpty() in the query.
Dim firstMonth2 As Integer = months.AsQueryable().DefaultIfEmpty(1).First()
MsgBox(String.Format("The value of the firstMonth2 variable is {0}", firstMonth2))

' This code produces the following output:
'
' The value of the firstMonth1 variable is 1
' The value of the firstMonth2 variable is 1

Uwagi

Metoda FirstOrDefault<TSource>(IQueryable<TSource>) generuje element MethodCallExpression , który reprezentuje wywołanie FirstOrDefault<TSource>(IQueryable<TSource>) siebie jako skonstruowaną metodę ogólną. Następnie przekazuje MethodCallExpression element do Execute<TResult>(Expression) metody reprezentowanej IQueryProvider przez Provider właściwość parametru source .

Zachowanie zapytania, które występuje w wyniku wykonania drzewa wyrażeń, które reprezentuje wywołanie FirstOrDefault<TSource>(IQueryable<TSource>) , zależy od implementacji typu parametru source . Oczekiwane zachowanie polega na tym, że zwraca pierwszy element w sourceobiekcie lub wartość domyślną, jeśli source jest pusta.

Metoda FirstOrDefault nie zapewnia sposobu określenia wartości domyślnej, która ma być zwracana, jeśli source jest pusta. Jeśli chcesz określić wartość domyślną inną niż default(TSource), użyj DefaultIfEmpty<TSource>(IQueryable<TSource>, TSource) metody zgodnie z opisem w sekcji Przykład.

Dotyczy

FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>)

Źródło:
Queryable.cs
Źródło:
Queryable.cs
Źródło:
Queryable.cs

Zwraca pierwszy element sekwencji, który spełnia określony warunek lub wartość domyślną, jeśli taki element nie zostanie znaleziony.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate);
public static TSource FirstOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
public static TSource? FirstOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate);
static member FirstOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean))) As TSource

Parametry typu

TSource

Typ elementów elementu source.

Parametry

source
IQueryable<TSource>

Element do IQueryable<T> zwrócenia elementu z.

predicate
Expression<Func<TSource,Boolean>>

Funkcja testowania każdego elementu na stanie.

Zwraca

TSource

default(TSource) jeśli source jest pusty lub jeśli żaden element nie przeszedł testu określonego przez predicate; w przeciwnym razie pierwszy element w source tym przechodzi test określony przez predicate.

Wyjątki

source lub predicate to null.

Przykłady

W poniższym przykładzie kodu pokazano, jak używać FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) , przekazując predykat. W drugim zapytaniu nie ma elementu w sekwencji, który spełnia warunek.

string[] names = { "Hartono, Tommy", "Adams, Terry",
                     "Andersen, Henriette Thaulow",
                     "Hedlund, Magnus", "Ito, Shu" };

// Get the first string in the array that is longer
// than 20 characters, or the default value for type
// string (null) if none exists.
string firstLongName =
    names.AsQueryable().FirstOrDefault(name => name.Length > 20);

Console.WriteLine("The first long name is '{0}'.", firstLongName);

// Get the first string in the array that is longer
// than 30 characters, or the default value for type
// string (null) if none exists.
string firstVeryLongName =
    names.AsQueryable().FirstOrDefault(name => name.Length > 30);

Console.WriteLine(
    "There is {0} name that is longer than 30 characters.",
    string.IsNullOrEmpty(firstVeryLongName) ? "NOT a" : "a");

/*
    This code produces the following output:

    The first long name is 'Andersen, Henriette Thaulow'.
    There is NOT a name that is longer than 30 characters.
*/
Dim names() As String = {"Hartono, Tommy", "Adams, Terry", _
                     "Andersen, Henriette Thaulow", _
                     "Hedlund, Magnus", "Ito, Shu"}

' Get the first string in the array that is longer
' than 20 characters, or the default value for type
' string (null) if none exists.
Dim firstLongName As String = _
            names.AsQueryable().FirstOrDefault(Function(name) name.Length > 20)

MsgBox(String.Format("The first long name is '{0}'.", firstLongName))

' Get the first string in the array that is longer
' than 30 characters, or the default value for type
' string (null) if none exists.
Dim firstVeryLongName As String = _
    names.AsQueryable().FirstOrDefault(Function(name) name.Length > 30)

MsgBox(String.Format( _
    "There is {0} name that is longer than 30 characters.", _
    IIf(String.IsNullOrEmpty(firstVeryLongName), "NOT a", "a")))

' This code produces the following output:
'
' The first long name is 'Andersen, Henriette Thaulow'.
' There is NOT a name that is longer than 30 characters.

Uwagi

Ta metoda ma co najmniej jeden parametr typu Expression<TDelegate> , którego argument typu jest jednym z Func<T,TResult> typów. W przypadku tych parametrów można przekazać wyrażenie lambda i zostanie skompilowane do elementu Expression<TDelegate>.

Metoda FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) generuje element MethodCallExpression , który reprezentuje wywołanie FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) siebie jako skonstruowaną metodę ogólną. Następnie przekazuje MethodCallExpression element do Execute<TResult>(Expression) metody reprezentowanej IQueryProvider przez Provider właściwość parametru source .

Zachowanie zapytania, które występuje w wyniku wykonania drzewa wyrażeń, które reprezentuje wywołanie FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>) , zależy od implementacji typu parametru source . Oczekiwane zachowanie polega na tym, że zwraca pierwszy element, który spełnia warunek w sourcepredicateelemecie , lub wartość domyślną, jeśli żaden element nie spełnia warunku.

Dotyczy

FirstOrDefault<TSource>(IQueryable<TSource>, TSource)

Źródło:
Queryable.cs
Źródło:
Queryable.cs
Źródło:
Queryable.cs

Zwraca pierwszy element sekwencji lub wartość domyślną, jeśli sekwencja nie zawiera żadnych elementów.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source, TSource defaultValue);
public static TSource FirstOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, TSource defaultValue);
static member FirstOrDefault : System.Linq.IQueryable<'Source> * 'Source -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource), defaultValue As TSource) As TSource

Parametry typu

TSource

Typ elementów elementu source.

Parametry

source
IQueryable<TSource>

Element IEnumerable<T> , aby zwrócić pierwszy element.

defaultValue
TSource

Wartość domyślna, która ma być zwracana, jeśli sekwencja jest pusta.

Zwraca

TSource

defaultValue jeśli source jest pusty; w przeciwnym razie pierwszy element w sourceelemecie .

Wyjątki

source to null.

Dotyczy

FirstOrDefault<TSource>(IQueryable<TSource>, Expression<Func<TSource,Boolean>>, TSource)

Źródło:
Queryable.cs
Źródło:
Queryable.cs
Źródło:
Queryable.cs

Zwraca pierwszy element sekwencji, który spełnia warunek lub wartość domyślną, jeśli taki element nie zostanie znaleziony.

public:
generic <typename TSource>
[System::Runtime::CompilerServices::Extension]
 static TSource FirstOrDefault(System::Linq::IQueryable<TSource> ^ source, System::Linq::Expressions::Expression<Func<TSource, bool> ^> ^ predicate, TSource defaultValue);
public static TSource FirstOrDefault<TSource> (this System.Linq.IQueryable<TSource> source, System.Linq.Expressions.Expression<Func<TSource,bool>> predicate, TSource defaultValue);
static member FirstOrDefault : System.Linq.IQueryable<'Source> * System.Linq.Expressions.Expression<Func<'Source, bool>> * 'Source -> 'Source
<Extension()>
Public Function FirstOrDefault(Of TSource) (source As IQueryable(Of TSource), predicate As Expression(Of Func(Of TSource, Boolean)), defaultValue As TSource) As TSource

Parametry typu

TSource

Typ elementów elementu source.

Parametry

source
IQueryable<TSource>

Element do IEnumerable<T> zwrócenia elementu z.

predicate
Expression<Func<TSource,Boolean>>

Funkcja testowania każdego elementu na stanie.

defaultValue
TSource

Wartość domyślna, która ma być zwracana, jeśli sekwencja jest pusta.

Zwraca

TSource

defaultValue jeśli source jest pusty lub jeśli żaden element nie przejdzie testu określonego przez predicate; w przeciwnym razie pierwszy element w source tym przechodzi test określony przez predicate.

Wyjątki

source lub predicate to null.

Dotyczy