Để ép kiểu (cast) các phần tử, dùng phương thức Cast().
Đây là danh sách của chúng ta.
List<object> myList = new List<object> { "Mac", "Windows", "Linux", "Solaris" };
Bây giờ, ép kiểu và dùng phương thức Cast() với phương thức substring() để hiển thị 2 ký tự đầu của mỗi chuỗi trong danh sách.
IEnumerable<string> res = myList.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
Hãy xem ví dụ hoàn chỉnh.
Ví dụ
using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
static void Main() {
List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" };
// lấy 2 chữ cái đầu từ mỗi chuỗi
IEnumerable<string> res = list.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
foreach (string str in res)
Console.WriteLine(str);
}
}
Kết quả
ke mo jo mo