LINQ to Entities 查詢中的標準查詢運算子Standard Query Operators in LINQ to Entities Queries

在查詢中,您可以指定要從資料來源擷取的資訊。In a query, you specify the information that you want to retrieve from the data source. 此外,查詢也可以指定該項資訊傳回之前應該如何排序、分組和成形。A query can also specify how that information should be sorted, grouped, and shaped before it is returned. LINQ 提供一組可在查詢中使用的標準查詢方法。LINQ provides a set of standard query methods that you can use in a query. 這些方法大多會在序列上運作;在此內容中,序列是一種物件,其型別會實作為 IEnumerable<T> 介面或 IQueryable<T> 介面。Most of these methods operate on sequences; in this context, a sequence is an object whose type implements the IEnumerable<T> interface or the IQueryable<T> interface. 標準查詢運算子的查詢功能包括篩選、投影、彙總、排序、群組、分頁等等。The standard query operators query functionality includes filtering, projection, aggregation, sorting, grouping, paging, and more. 某些更常用的標準查詢運算子具有專用的關鍵字語法,因此可以使用查詢運算式語法來呼叫它們。Some of the more frequently used standard query operators have dedicated keyword syntax so that they can be called by using query expression syntax. 相較於以方法為根據的同等項目,查詢運算式是一個不同且更具可讀性之表示查詢的方式。A query expression is a different, more readable way to express a query than the method-based equivalent. 查詢運算式子句會在編譯時期轉譯成查詢方法的呼叫。Query expression clauses are translated into calls to the query methods at compile time. 如需具有對等查詢運算式子句的標準查詢運算子清單,請參閱 標準查詢運算子總覽For a list of standard query operators that have equivalent query expression clauses, see Standard Query Operators Overview.

LINQ to Entities 查詢不支援所有標準查詢運算子。Not all of the standard query operators are supported in LINQ to Entities queries. 如需詳細資訊,請參閱 支援和不支援的 LINQ 方法 (LINQ to Entities) For more information, see Supported and Unsupported LINQ Methods (LINQ to Entities). 本主題提供 LINQ to Entities 特定的標準查詢運算子的相關資訊。This topic provides information about the standard query operators that is specific to LINQ to Entities. 如需 LINQ to Entities 查詢已知問題的詳細資訊,請參閱 LINQ to Entities 中的已知問題和考慮For more information about known issues in LINQ to Entities queries, see Known Issues and Considerations in LINQ to Entities.

投影及篩選方法Projection and Filtering Methods

投射 是指將結果集的元素轉換成所需的表單。Projection refers to transforming the elements of a result set into a desired form. 例如,您可以從結果集中的每一個物件投影您需要的屬性子集,也可以投影屬性並針對它執行數學計算,或是從結果集投影整個物件。For example, you can project a subset of the properties you need from each object in the result set, you can project a property and perform a mathematical calculation on it, or you can project the entire object from the result set. 投影方法為 SelectSelectManyThe projection methods are Select and SelectMany.

篩選 是指將結果集限制為只包含符合指定條件之元素的作業。Filtering refers to the operation of restricting the result set to contain only those elements that match a specified condition. 篩選方法為 WhereThe filtering method is Where.

LINQ to Entities 中支援投射和篩選方法的大部分多載,但接受位置引數的多載除外。Most overloads of the projection and filtering methods are supported in LINQ to Entities, with the exception of those that accept a positional argument.

聯結方法Join Methods

在以彼此沒有可瀏覽關聯性之資料來源為目標的查詢中,聯結是一項重要的作業。Joining is an important operation in queries that target data sources that have no navigable relationships to each other. 兩個資料來源的聯結是指某個資料來源中的物件與另一個資料來源中共用相同屬性 (Attribute) 或屬性 (Property) 之物件的關聯。A join of two data sources is the association of objects in one data source with objects in the other data source that share a common attribute or property. 聯結方法為 JoinGroupJoinThe join methods are Join and GroupJoin.

大多數聯結方法的多載都有支援,但是使用 IEqualityComparer<T> 的多載除外。Most overloads of the join methods are supported, with the exception of those that use a IEqualityComparer<T>. 這是因為比較子 (Comparer) 無法轉譯成資料來源。This is because the comparer cannot be translated to the data source.

設定方法Set Methods

LINQ 中的 Set 作業是指一種查詢作業,這種作業會讓其結果集根據相同或另一個集合中是否有同等項目存在而定。Set operations in LINQ are query operations that base their result sets on the presence or absence of equivalent elements within the same or in another collection (or set). Set 方法為 AllAnyConcatContainsDefaultIfEmptyDistinctEqualAllExceptIntersectUnionThe set methods are All, Any, Concat, Contains, DefaultIfEmpty, Distinct, EqualAll, Except, Intersect, and Union.

LINQ to Entities 中支援 set 方法的大部分多載,但相較于 LINQ to Objects 的行為有一些差異。Most overloads of the set methods are supported in LINQ to Entities, though there are some differences in behavior compared to LINQ to Objects. 但是,不支援使用來設定方法, IEqualityComparer<T> 因為比較子無法轉譯成資料來源。However, set methods that use an IEqualityComparer<T> are not supported because the comparer cannot be translated to the data source.

排序方法Ordering Methods

排序指的是根據一或多個屬性來排序結果集的項目。Ordering, or sorting, refers to the ordering the elements of a result set based on one or more attributes. 藉由指定一個以上的排序準則,就可以中斷群組內的繫結。By specifying more than one sort criterion, you can break ties within a group.

大多數排序方法的多載都有支援,但是使用 IComparer<T> 的多載除外。Most overloads of the ordering methods are supported, with the exception of those that use an IComparer<T>. 這是因為比較子 (Comparer) 無法轉譯成資料來源。This is because the comparer cannot be translated to the data source. 排序方法為 OrderByOrderByDescendingThenByThenByDescendingReverseThe ordering methods are OrderBy, OrderByDescending, ThenBy, ThenByDescending, and Reverse.

因為查詢是在資料來源上執行,所以排序行為可能會與 CLR 中執行的查詢不同。Because the query is executed on the data source, the ordering behavior may differ from queries executed in the CLR. 這是因為排序選項 (例如大小寫排序、漢字排序和 null 排序) 可以在資料來源中設定。This is because ordering options, such as case ordering, kanji ordering, and null ordering, can be set in the data source. 視資料來源的不同,這些排序選項可能會產生與 CLR 中不同的結果。Depending on the data source, these ordering options might produce different results than in the CLR.

如果您在一個以上的排序作業中指定相同的索引鍵選取器,將會產生重複的排序。If you specify the same key selector in more than one ordering operation, a duplicate ordering will be produced. 這是無效的,而且將會擲回例外狀況。This is not valid and an exception will be thrown.

群組方法Grouping Methods

群組指的是將資料放在群組中,好讓每一個群組中的項目都可共用共同的屬性。Grouping refers to placing data into groups so that the elements in each group share a common attribute. 此群組方法為 GroupByThe grouping method is GroupBy.

大多數群組方法的多載都有支援,但是使用 IEqualityComparer<T> 的多載除外。Most overloads of the grouping methods are supported, with the exception of those that use an IEqualityComparer<T>. 這是因為比較子 (Comparer) 無法轉譯成資料來源。This is because the comparer cannot be translated to the data source.

群組方法會使用索引鍵選取器的不同子查詢對應到資料來源。The grouping methods are mapped to the data source using a distinct sub-query for the key selector. 索引鍵選取器比較子查詢是使用資料來源的語意來執行,包括與比較 null 值有關的問題。The key selector comparison sub-query is executed by using the semantics of the data source, including issues related to comparing null values.

彙總方法Aggregate Methods

彙總運算會計算值集合中的單一值。An aggregation operation computes a single value from a collection of values. 例如,當您使用一個月中每天的溫度值來計算每天平均溫度時,您就執行了一項彙總運算。For example, calculating the average daily temperature from a month's worth of daily temperature values is an aggregation operation. 彙總方法為 AggregateAverageCountLongCountMaxMinSumThe aggregate methods are Aggregate, Average, Count, LongCount, Max, Min, and Sum.

大多數彙總方法的多載都有支援。Most overloads of the aggregate methods are supported. 如果是與 null 值有關的行為,彙總方法會使用資料來源語意。For behavior related to null values, the aggregate methods use the data source semantics. 當牽涉到 null 值時的彙總方法行為可能會有不同 (根據使用哪一個後端資料來源而定)。The behavior of the aggregation methods when null values are involved might be different, depending on which back-end data source is being used. 使用資料來源語意的彙總方法行為也可能會與 CLR 方法預期的行為不同。Aggregate method behavior using the semantics of the data source might also be different from what is expected from CLR methods. 例如,SQL Server 上 Sum 方法的預設行為是要忽略所有 null 值,而不是擲回例外狀況。For example, the default behavior for the Sum method on SQL Server is to ignore any null values instead of throwing an exception.

彙總產生的所有例外狀況 (例如 Sum 函式中的溢位) 會在具體化查詢結果期間顯示為資料來源例外狀況或是 Entity Framework 例外狀況。Any exceptions that result from aggregation, such as an overflow from the Sum function, are thrown as data source exceptions or Entity Framework exceptions during the materialization of the query results.

對於牽涉到序列計算的方法而言 (例如 SumAverage),實際的計算會在伺服器上執行。For those methods that involve a calculation over a sequence, such as Sum or Average, the actual calculation is performed on the server. 因此,型別轉換和精確度的喪失可能會在伺服器上發生,而且結果可能會與使用 CLR 語意所預期的結果不同。As a result, type conversions and loss of precision might occur on the server, and the results might differ from what is expected using CLR semantics.

null/非 null 值之彙總方法的預設行為顯示於下表:The default behavior of the aggregate methods for null/non-null values is shown in the following table:

方法Method 無資料No data 所有 null 值All null values 某些 null 值Some null values 無 null 值No null values
Average 傳回 null。Returns null. 傳回 null。Returns null. 傳回序列中非 Null 值的平均值。Returns the average of the non-null values in a sequence. 計算數值序列的平均值。Computes the average of a sequence of numeric values.
Count 傳回 0Returns 0 傳回序列中 null 值的數目。Returns the number of null values in the sequence. 傳回序列中 null 值與非 null 值的數目。Returns the number of null and non-null values in the sequence. 傳回序列中的項目數。Returns the number of elements in the sequence.
Max 傳回 null。Returns null. 傳回 null。Returns null. 傳回序列中最大的非 null 值。Returns the maximum non-null value in a sequence. 傳回序列中的最大值。Returns the maximum value in a sequence.
Min 傳回 null。Returns null. 傳回 null。Returns null. 傳回序列中最小的非 null 值。Returns the minimum non-null value in a sequence. 傳回序列中的最小值。Returns the minimum value in a sequence.
Sum 傳回 null。Returns null. 傳回 null。Returns null. 傳回序列中非 null 值的總和。Returns the sum of the non-null value in a sequence. 計算數值序列的總和。Computes the sum of a sequence of numeric values.

型別方法Type Methods

Entity Framework 的內容都支援處理類型轉換和測試的兩個 LINQ 方法。The two LINQ methods that deal with type conversion and testing are both supported in the context of the Entity Framework. 這表示,唯一支援的類型是對應至適當 Entity Framework 類型的類型。This means that the only supported types are types that map to the appropriate Entity Framework type. 如需這些類型的清單,請參閱 (CSDL) 的概念模型類型 For a list of these types, see Conceptual Model Types (CSDL). 型別方法為 ConvertOfTypeThe type methods are Convert and OfType.

實體類型支援 OfTypeOfType is supported for entity types. 概念模型基本型別支援 ConvertConvert is supported for conceptual model primitive types. 也支援 C# isas 方法。The C# is and as methods are also supported.

分頁方法Paging Methods

分頁作業會從序列傳回單一元素或多個元素。Paging operations return a single element or multiple elements from a sequence. 支援的分頁方法為 FirstFirstOrDefaultSingleSingleOrDefaultSkipTakeThe supported paging methods are First, FirstOrDefault, Single, SingleOrDefault, Skip, and Take.

因為無法將函式對應至資料來源,或在資料來源上缺少集合的隱含順序,所以不支援許多分頁方法。A number of paging methods are not supported, due either to the inability to map functions to the data source or to the lack of implicit ordering of sets on the data source. 傳回預設值的方法限制為具有 null 預設值的概念模型基本型別及參考型別。Methods that return a default value are restricted to conceptual model primitive types and reference types with null defaults. 在空序列上執行的分頁方法將會傳回 null。Paging methods that are executed on an empty sequence will return null.

另請參閱See also