C#Cast方法
要投射元素,请使用Cast()方法。
以下是我们的列表。
List<object> myList = new List<object> { "Mac", "Windows", "Linux", "Solaris" };现在,强制转换并使用Cast()with方法与substring()method一起显示列表中每个字符串的前两个字母。
IEnumerable<string> res = myList.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
让我们看完整的例子。
示例
using System;
using System.Linq;
using System.Collections.Generic;
class Demo {
static void Main() {
List<object> list = new List<object> { "keyboard", "mouse", "joystick", "monitor" };
//从每个字符串中获取前2个字母
IEnumerable<string> res = list.AsQueryable().Cast<string>().Select(str => str.Substring(0, 2));
foreach (string str in res)
Console.WriteLine(str);
}
}输出结果
ke mo jo mo