共用方式為


Queryable.Cast<TResult>(IQueryable) 方法

定義

將 的 IQueryable 元素轉換為指定的類型。

public:
generic <typename TResult>
[System::Runtime::CompilerServices::Extension]
 static System::Linq::IQueryable<TResult> ^ Cast(System::Linq::IQueryable ^ source);
public static System.Linq.IQueryable<TResult> Cast<TResult>(this System.Linq.IQueryable source);
[System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
public static System.Linq.IQueryable<TResult> Cast<TResult>(this System.Linq.IQueryable source);
static member Cast : System.Linq.IQueryable -> System.Linq.IQueryable<'Result>
[<System.Diagnostics.CodeAnalysis.RequiresDynamicCode("Enumerating collections as IQueryable can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")>]
static member Cast : System.Linq.IQueryable -> System.Linq.IQueryable<'Result>
<Extension()>
Public Function Cast(Of TResult) (source As IQueryable) As IQueryable(Of TResult)

類型參數

TResult

將 的 source 元素轉換成 的類型。

參數

source
IQueryable

IQueryable 包含要轉換的元素。

傳回

IQueryable<TResult>

包含 IQueryable<T> 來源序列中每個元素轉換為指定型別的 。

屬性

例外狀況

sourcenull

序列中的元素無法被鑄造為型別 TResult

範例

以下程式碼範例示範如何將 Cast<TResult>(IQueryable) 序列中的物件轉換為型別 String


// Create a list of objects.
List<object> words =
    new List<object> { "green", "blue", "violet" };

// Cast the objects in the list to type 'string'
// and project the first letter of each string.
IEnumerable<string> query =
    words.AsQueryable()
    .Cast<string>()
    .Select(str => str.Substring(0, 1));

foreach (string s in query)
    Console.WriteLine(s);

/*  This code produces the following output:

    g
    b
    v
*/

' Create a list of objects.
Dim words As New List(Of Object)(New Object() {"green", "blue", "violet"})

' Cast the objects in the list to type 'string'
' and project the first letter of each string.
Dim query As IEnumerable(Of String) = _
    words.AsQueryable() _
            .Cast(Of String)() _
            .Select(Function(str) str.Substring(0, 1))

For Each s As String In query
    MsgBox(s)
Next

' This code produces the following output:
'
' g
' b
' v

備註

Cast<TResult>(IQueryable) 方法產生的 是 MethodCallExpression ,代表 Cast<TResult>(IQueryable) 呼叫本身為一個構造化的泛型方法。 接著將 傳遞MethodCallExpressionCreateQuery(Expression)IQueryProvider由參數Provider性質source所表示的方法。

執行代表呼叫 Cast<TResult>(IQueryable) 的表達式樹所產生的查詢行為,取決於參數型別 source 的實作。 預期行為是將 中的 source 值轉換成型別 TResult

適用於