Queryable.Cast<TResult>(IQueryable) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將 的 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<T> 來源序列中每個元素轉換為指定型別的 。
- 屬性
例外狀況
source 為 null。
序列中的元素無法被鑄造為型別 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) 呼叫本身為一個構造化的泛型方法。 接著將 傳遞MethodCallExpression給CreateQuery(Expression)IQueryProvider由參數Provider性質source所表示的方法。
執行代表呼叫 Cast<TResult>(IQueryable) 的表達式樹所產生的查詢行為,取決於參數型別 source 的實作。 預期行為是將 中的 source 值轉換成型別 TResult。