I made a call to two different methods that returns a list both of different types. I then combined the lists into an array thus making an array of two different types of objects. Now I'm trying to loop over that array using a foreach
loop but for each item in the array, I need to access it's unique properties. Is there any way to do this?
List<TypeA> typeAVariable = SomeMethod();
List<TypeB> typeBVariable = AnotherMethod();
var arr = new ArrayList();
arr.AddRange(typeAVariable);
arr.AddRange(typeBVariable);
foreach(var item in arr)
{
if(item.typeOf == typeAVariable)
{
item.typeAVariableProperty;
}
else
{
item.typeBVariableProperty;
}
}
If you really have to combine items of different types into obsolete ArrayList
collection ( List<Object>
is a better choice), you can try pattern matching to get itemA
and itemB
back:
foreach(var item in arr)
{
if (item is TypeA itemA)
{
itemA.typeAVariableProperty;
}
else if (item is TypeB itemB)
{
itemB.typeBVariableProperty;
}
}
You can write it like this:
switch (item)
{
case TypeA typeA:
typeA.typeAVariableProperty
// do sth
break;
case TypeB typeB:
typeB.typeBVariableProperty
// do sth
break;
}
Switch statements can be faster than an if-else-structure. See: Is there any significant difference between using if/else and switch-case in C#?
Create an (abstract) base class and let both classes inherit from the base class. Then create a List<BaseClass>
that can contains both types.
abstract class BaseClass
{
}
class TypeA : BaseClass
{
public int AnIntroperty { get; set; }
}
class TypeB : BaseClass
{
public string AStringroperty { get; set; }
}
Then use it like this:
List<TypeA> typeAVariable = SomeMethod();
List<TypeB> typeBVariable = AnotherMethod();
var combinedList = List<BaseClass>();
combinedList.AddRange(typeAVariable);
combinedList.AddRange(typeBVariable);
foreach (var item in combinedList)
{
if (item is TypeA typeAItem)
{
typeAItem.AnIntroperty;
}
else if (item is TypeB typeBItem)
{
typeBItem.AStringroperty;
}
}
I think I would use as
to cast your object before checking if it's null or not. Like this:
foreach(var item in arr)
{
var convertedItem = item as typeAVariable;
if(convertedItem == null)
{
// Do what you need for B type
(typeBVariable)item.typeBVariableProperty;
continue;
}
// Do what you need for A type
convertedItem.typeAVariableProperty;
}
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.