C# Cast 方法
若要转换元素,请使用 Cast() 方法。
以下是我们的列表。
List<object> myList = new List<object> { "Mac", "Windows", "Linux", "Solaris" };现在,对列表中的每个字符串使用 Cast() 方法进行转换并使用 substring() 方法来显示前两个字母。
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" };
// getting first 2 letters from every string
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
Advertisements
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP