Cho phép chuyển kiểu của các đối tượng đầu vào và được dùng trong một phạm vi đa dạng các ứng dụng.
Toán tử thuộc nhóm này chỉ xét Cast, các toán tử khác không hỗ trợ trong C# hay VB:
Toán tử | Mô tả | Cú pháp C# | Cú pháp VB |
AsEnumerable | Trả về kiểu IEnumerable <T> | Chưa hỗ trợ | Chưa hỗ trợ |
AsQueryable | Chuyển từ kiểu Ienumerable <T> đến Iqueryable | Chưa hỗ trợ | Chưa hỗ trợ |
Cast | Thực hiện chuyển kiểu một đối tượng sang kiểu khác. | Dùng biến kiểu tường minh | From…As |
OfType | Chuyển đến một kiểu bất kỳ. | Chưa hỗ trợ | Chưa hỗ trợ |
ToArray | Chuyển đến kiểu mảng. | Chưa hỗ trợ | Chưa hỗ trợ |
ToDictionary | Chuyển đến kiểu Dictionary <Tkey, TValue> | Chưa hỗ trợ | Chưa hỗ trợ |
ToList | Chuyển đến kiểu danh sách List <T> | Chưa hỗ trợ | Chưa hỗ trợ |
ToLookup | Chuyển đến một Lookup <Tkey, TElement> | Chưa hỗ trợ | Chưa hỗ trợ |
Ví dụ Cast với C#:
// nguồn dữ liệu Plant[] plants = new Plant[] { new CarnivorousPlant { Name = "Venus Fly Trap", TrapType = "Snap Trap" }, new CarnivorousPlant { Name = "Pitcher Plant", TrapType = "Pitfall Trap" }, new CarnivorousPlant { Name = "Sundew", TrapType = "Flypaper Trap" }, new CarnivorousPlant { Name = "Waterwheel Plant", TrapType = "Snap Trap" }}; // tạo truy vấn var query = from CarnivorousPlant cPlant in plants where cPlant.TrapType == "Snap Trap" select cPlant; // thực thi truy vấn foreach (var e in query) { Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType); } class Plant { public string Name { get; set; } } class CarnivorousPlant : Plant { public string TrapType { get; set; } }
LINQPad
Ví dụ Cast với VB:
Sub Main // nguồn dữ liệu Dim plants() As Plant = {New CarnivorousPlant With {.Name = "Venus Fly Trap", .TrapType = "Snap Trap"}, New CarnivorousPlant With {.Name = "Pitcher Plant", .TrapType = "Pitfall Trap"}, New CarnivorousPlant With {.Name = "Sundew", .TrapType = "Flypaper Trap"}, New CarnivorousPlant With {.Name = "Waterwheel Plant", .TrapType = "Snap Trap"}} // tạo truy vấn Dim list = From cPlant As CarnivorousPlant In plants Where cPlant.TrapType = "Snap Trap" Select cPlant // thực thi truy vấn For Each e In list Console.WriteLine("Name = {0} , Trap Type = {1}", e.Name, e.TrapType) Next End Sub Class Plant Public Property Name As String End Class Class CarnivorousPlant Inherits Plant Public Property TrapType As String End Class
LINQPad
Kết quả
Ý kiến bài viết