C# Cast 方法
csharpprogrammingserver side programming
要转换元素,请使用 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" }; // 从每个字符串中获取前 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