@Benjamin Chew , Welcome to Microsoft Q&A, after my attempt, I find it is hard to access property's value by using the index and property via ArrayList or Dictionary. If you really want to do it, I recommend that you could convert your list to datatable, which may get you what you wanted.
Here is a code example you could refer to.
static void Main(string[] args)
{
List<Agency> list = new List<Agency>();
list.Add(new Agency { AgencyId = new Guid(), AgencyName = "test1", Acronym = "aa", EntityType = 1, EmailAddress = "******@hotmail.com" });
list.Add(new Agency { AgencyId = new Guid(), AgencyName = "test2", Acronym = "bb", EntityType = 2, EmailAddress = "******@hotmail.com" });
list.Add(new Agency { AgencyId = new Guid(), AgencyName = "test3", Acronym = "cc", EntityType = 3, EmailAddress = "******@hotmail.com" });
DataTable table = ToDataTable<Agency>(list);
string strAgenciyName = "AgencyName";
for (int i = 0; i < table.Rows.Count; i++)
{
Console.WriteLine(table.Rows[i][strAgenciyName]);
}
}
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
Result:
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.