我有一些清单:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
Run Code Online (Sandbox Code Playgroud)
我想对我列表中的元素应用一些转换.我可以通过两种方式做到这一点:
List<int> list1 = list.Select(x => 2 * x).ToList();
List<int> list2 = list.ConvertAll(x => 2 * x).ToList();
Run Code Online (Sandbox Code Playgroud)
这两种方式有什么区别?
我有一个object值可能是像int[]或的几种数组类型之一string[],我想将它转换为string[].我的第一次尝试失败了
void Do(object value)
{
if (value.GetType().IsArray)
{
object[] array = (object[])value;
string[] strings = Array.ConvertAll(array, item => item.ToString());
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
运行时错误Unable to cast object of type 'System.Int32[]' to type 'System.Object[]',回想起来很有意义,因为我int[]不包含盒装整数.
我四处寻找这个工作版本:
void Do(object value)
{
if (value.GetType().IsArray)
{
object[] array = ((Array)value).Cast<object>().ToArray();
string[] strings = Array.ConvertAll(array, item => item.ToString());
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我想这没关系,但看起来很复杂.谁有更简单的方法?