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);
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) 參數的 屬性所Provider表示的 source 方法IQueryProvider

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

適用於