2016-11-17 28 views
2

我有一个ArrayList,需要将ArrayList的项添加到字符串列表中。我试过如下:C#将ArrayList转换为字符串列表?

listString.AddRange(new List<string>((string[])this.arrayList.ToArray())) 

但是这给

无法投类型的对象System.Object的[]'键入 'System.String []'

异常

请注意:;我无法使用.Cast,因为我在框架4.0中工作。

回答

3

使用ToArray(typeof(string))创建一个数组,然后将它添加到类型的变量之前将它转换为更具体的数组类型string[]List<string>

listString.AddRange((string[])this.arrayList.ToArray(typeof(string))); 
+0

这实际上工作。这是一个很大的帮助。非常感谢。 –

1

您必须将数组列表中的每个元素转换为一个字符串,以将它们添加到字符串列表中。这样做的更好的选择是这样的:

listString.AddRange(arrayList.ToArray().Select(x => x.ToString()).ToList()); 
+0

我无法使用Select/Cast/ToList()。 ArrayList中没有这些全部的定义。但是,SveinFidjestøl给出的答案奏效了。 –

+0

为了使它工作,你必须添加'使用System.Linq;'到使用部分 –

2

LINQ到对象有一个铸造方法,它返回T的IEnumerable的,所有的类型都被蒙上(假设转换是有效的),所以我提示:

this.ArrayList.Cast<string>().ToList(); 

,或者,如果你listString已经存在:

listString.AddRange(this.ArrayList.Cast<string>()); 
+0

是的,我做到了。但在Cast()上检查[MSDN](https://msdn.microsoft.com/en-us/library/bb341406(v = vs.100).aspx)。它自3.5 – MarkO

-4

试图理解下面的代码:此代码解决问题。

ArrayList myAL = new ArrayList(); 
myAL.Add("The"); 
myAL.Add("quick");  
myAL.Add("brown"); 
myAL.Add("fox"); 

// Creates and initializes a new Queue. 
Queue myQueue = new Queue(); 
myQueue.Enqueue("jumped"); 
myQueue.Enqueue("over"); 

// Displays the ArrayList and the Queue. 
Console.WriteLine("The ArrayList initially contains the following:"); 
PrintValues(myAL, '\t'); 
Console.WriteLine("The Queue initially contains the following:"); 
PrintValues(myQueue, '\t'); 

// Copies the Queue elements to the end of the ArrayList. 
myAL.AddRange(myQueue); 
+0

以来一直支持。事实上,这很难理解。不知道为什么一个人会花时间“试着去理解”它...... –

1

在我看来,最保险的办法:

listString.AddRange(arrayList.ToArray().Select(e => e.ToString())); 
2

你可以试试下面的代码如下:

ArrayList al = new ArrayList(); 
List<string> lst = new List<string>(); 
foreach (string l in al) 
{ 
    lst.Add(l); 
} 
+0

这是正确的,但不是有效的方法。 –

0
ArrayList arrayList = new ArrayList {"A","B","C" }; 
List<string> listString = new List<string>(); 
foreach (string item in arrayList) 
{ 
    listString.Add(item); 
} 
var data = listString;