I’m trying to get a certain indexed item by number from a generic list and I’m getting: Unable to cast object of type ‘System.Collections.Generic.List1[typename]' to type 'System.Collections.Generic.List1[System.Object]’. errors.
What I’m trying to achieve is to loop (forward or backwards) to a certain list based upon a inherited baseclass; like so (or something similar anyway):
public class Fruit
{
public string Name {get;set;}
}
public class Apple : Fruit
{
public bool IsSour {get;set;}
}
public class Orange : Fruit
{
public bool Juicy {get;set;}
}
public List<Apple> Apples = new List<Apple>();
public List<Orange> Oranges = new List<Oranges>();
what I’d like to to is something like this:
public string[] BuildList(object GenericListHere, bool Backwards)
{
for(int i=GenericListHere.Length-1;i>=0;i--)
{
string MyName = GenericListHere[i].Name;
The above is somewhat pseudocoded, but I’d like to throw in either the apples or oranges list to get result.
I don’t know beforehand which object I’m getting, so I get the Count/Length like this (not psuedocoded) where TestObj is just the object I’m getting:
int iBound = -1;
try
{
System.Reflection.PropertyInfo oInfo = TestObj.GetType().GetProperty("Count");
iBound = (int)oInfo.GetValue(TestObj, null);
}
catch
{
And if the iBound >= 0 it’s a collection. The next part.. I’m somewhat lost…
if (iBound != -1)
{
int iLoopStart = (backwardsLoop ? iBound - 1 : 0);
int iLoopEnd = (backwardsLoop ? -1 : iBound);
int iLoopDifference = (backwardsLoop ? -1 : +1);
for (int iLoop = iLoopStart; iLoop != iLoopEnd; iLoop += iLoopDifference)
{
// THIS IS REALLY BAD CODED.. BUT I DONT GET IT
object VarCollection = TestObj;
object[] arInt = new object[1];
arInt.SetValue(iLoop, 0);
Type[] tArray = new Type[1];
tArray.SetValue(typeof(int), 0);
object oElem = ((System.Collections.Generic.List<object>)VarCollection)[iLoop];
What I’d really like is something like : VarCollection[iLoop], but that doesn’t seem to work..
Anyone experienced with these kind of lists? TIA!
Just cast it to
IListand use the indexer.