开发者

C# How to convert ArrayList of typed objects to a typed List?

I have an ArrayList of objects that are of a certain type, and I need to convert this ArrayList in to a types list. Here is my code

Type objType = Type.GetType(myTypeName);

ArrayList myArrayList = new ArrayList();

object myObj0 = Activator.CreateInstance(type);
object myObj1 = Activator.CreateInstance(type);
object myObj2 = Activator.CreateInstance(type);

myArrayList.Add(myObj0);
myArrayList.Add(myObj1);
myArrayList.Add(myObj2);

Array typedArray = myArrayList.ToArray(objType);  // this is typed
object returnValue = typedArray.ToList();  // this is fake, but this is what I am looking for

T开发者_如何学Chere is no ToList() available for an Array, this is the behaviour I am looking for

object returnValue = typedArray.ToList();

So basically I have the type name as a string, I can create a Type from the name, and create a collection containing several objects typed, but how do I convert that to a List? I am hydrating a property and when I do a SetValue my property type needs to match.

Thank you very much.


If you're using .NET 4, dynamic typing can help - it can perform type inference so you can call ToList, admittedly not as an extension method:

dynamic typedArray = myArrayList.ToArray(objType);    
object returnValue = Enumerable.ToList(typedArray);

Otherwise, you'll need to use reflection:

object typedArray = myArrayList.ToArray(objType);   
// It really helps that we don't need to work through overloads...
MethodInfo openMethod = typeof(Enumerable).GetMethod("ToList");
MethodInfo genericMethod = openMethod.MakeGenericMethod(objType);
object result = genericMethod.Invoke(null, new object[] { typedArray });


Create a

List<YourType> list = new List<YourType>;

and then

list.AddRange(yourArray); 


Use an extenstion method: .ToList<myType>()


Use the generic List<> type instead.


Does it have to be List<T> or would an IEnumerable<T> do?

Taking a little from Linq you could do:

object returnValue = myArrayList.Cast<string>();

Which creates the following object (assuming T = string):

System.Linq.Enumerable+<CastIterator>d__b1`1[System.String]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜