将 List(of object) 转换为 List(of string) 的方法是使用 LINQ 查询。以下是一个简单的示例,说明如何将 List(of object) 转换为 List(of string):
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<object> listOfObjects = new List<object> { "Apple", "Banana", "Orange", 1, 2.0, 'A' };
List<string> listOfStrings = listOfObjects
.Where(x => x.GetType() == typeof(string))
.Select(x => (string)x)
.ToList();
foreach (string str in listOfStrings)
{
Console.WriteLine(str);
}
}
}
在这个示例中,我们首先创建了一个包含不同类型的对象的 List(of object)。然后,我们使用 LINQ 查询筛选出类型为字符串的对象,并将其转换为 List(of string)。最后,我们遍历 List(of string) 并输出每个字符串。
这个示例中的代码可以很好地处理包含不同类型对象的 List(of object),并将其转换为 List(of string)。
领取专属 10元无门槛券
手把手带您无忧上云