2013-10-14 126 views
0

我一派,并处罚金此链接,但仍然没有工作 Convert List<T> to object[]如何将genericlist转换为一个对象数组 - > [对象]

我想转换为int的列表,以对象数组。为什么?因为我想在Combbox中添加列表作为对象数组,它就是参数。

问题是它在Combobox中仅添加“一个项目”Object []数组,而“tempList”包含4个int类型的项目。

我喜欢在对象[](对象数组)中添加4个项目,现在它添加为1项目,并在调试器中显示Object []数组。

当我看在调试器和类型:

客户 - 它显示对象[1],并且当I型

客户[0]它显示对象[4],因此实际上被添加4项,但我怎样才能得到这些值。

List<int> tempList= new CustomersRepository().GetAll().Select(a => a.Numero).ToList(); 
object[] customers = new object[] { tempList.Cast<object>().ToArray() }; 
ComboBox.Items.AddRange(customers); 
+0

你在哪里可以在'comboBox'上找到'AddRange'方法?我认为你的意思是'Items.AddRange' –

+0

是的,的确输入错误。它的combobox.items.addrange(xx),刚刚更正。 – ethem

回答

4

你正在做的是当前正在创建一个数组数组。所以访问值将通过以下来完成:

customers[0][1] 

我怀疑什么,你实际上是在寻找如下:

object[] customers = tempList.Cast<object>().ToArray(); 

这将创建一个名为customers对象项目的数组。

2

试试这样说:

var customers = tempList.Cast<object>().ToArray(); 

或者也有明确的转换:发生

var customers = tempList.Select(t => (object)t).ToArray(); 

的问题,因为你使用的是初始化为建立您的清单。

此语法:

var arr = new object[] { "a", "b" } 

初始化一个数组与两个字符串。

当你写

var arr = new object[] { tempList.Cast<object>().ToArray() } 

所以你建立一个数组的数组!

3
List<int> tempList= ...; 
object[] customers = tempList.Cast<Object>().ToArray(); 
2
object[] customers = new object[] { tempList.Cast<object>().ToArray() }; 

在这里你创建一个object[]有一个项目:另一object[]包含tempList的项目。


只需使用object[] customers = tempList.Cast<Object>().ToArray()代替另一object[]包装它。

0

如果您想要进一步处理并稍后获取数组,请不要使用ToList()。 像这样的东西应该是更有效:

var temp = new CustomersRepository().GetAll().Select(a => a.Numero); 
object[] customers = temp.Cast<object>().ToArray(); 
ComboBox.Items.AddRange(customers); 

只好临时被引用类型的集合,你不必投所有,但依靠阵列协方差。这应该工作:

var temp = new CustomersRepository().GetAll().Select(a => a.StringProperty); 
object[] customers = temp.ToArray(); //no need of Cast<object> 
ComboBox.Items.AddRange(customers); 

但是,这并不在你的情况,因为array covariance doesnt support for value types工作。


另一个想法是有一个扩展方法AddRange接受任何IEnumerable,不只是object[]。喜欢的东西:

public static void AddRange(this IList list, IEnumerable lstObject) 
{ 
    foreach (T t in lstObject) 
     list.Add(t); 
} 

现在,您可以拨打:

var customers = new CustomersRepository().GetAll().Select(a => a.Numero); 
ComboBox.Items.AddRange(customers); 

所有最好的是将Customer的add因为如此,并设置DisplayMemberValueMember属性你的财产,如Numero。既然你有组合框中的所有对象,你就有更多的信息。例如:

ComboBox.DisplayMember = "Numero"; 
var customers = new CustomersRepository().GetAll(); 
ComboBox.Items.AddRange(customers); // using the above extension method 
相关问题