1

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;
    }

}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
drethedevjs
  • 404
  • 2
  • 4
  • 15

4 Answers4

1

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;
    }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

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#?

0

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;
    }
}
Stefan
  • 652
  • 5
  • 19
0

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;

}