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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短