I have ArrayList which contains 4 items. each item is of type List<object>
. I am trying to get first item from ArrayList using below code. but it throws error
Unable to cast object of type 'System.Collections.Generic.List
1[System.Object]' to type 'System.Collections.Generic.List
1[CustomType]
calling code -
ArrayList arrayList = BusinessLayer.GetData();
List<CustomType> tempList = (List<CustomType>)arrayList[0];
called code logic -
if (connection.State == System.Data.ConnectionState.Closed)
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "EXEC SP_GET_DATA @id";
command.Parameters.Add(new SqlParameter("@id", id));
using (var reader = command.ExecuteReader())
{
var customTypeList = ((IObjectContextAdapter)context)
.ObjectContext
.Translate<object>(reader)
.ToList();
arrayList.Add(customTypeList);
reader.NextResult();
var customType2List = ((IObjectContextAdapter)context)
.ObjectContext
.Translate<object>(reader)
.ToList();
arrayList.Add(customType2List);
}
I am returning arraylist and want to get data back at calling code. I don't want to use model in called code. I understand that, we can use model at called code but I have to verify whether using ArrayList, can we get data back? I hope I explained clearly.
here I am trying to cast List<object>
from ArrayList to List<CustomType>
You have to explicitly cast back to List of Object first. Then use Cast to the custom type.
ArrayList arrayList = new();
arrayList.Add(new List<object>() { new Person() { FirstName = "Bob", LastName = "NewHart"} });
var tempList = ((List<object>)arrayList[0]).Cast<Person>().ToList();
Console.WriteLine(tempList[0].FirstName);
Console.ReadLine();
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.