0

I am trying to create an ArrayList from two Lists that have their objects extracted from a database in SQL Server.

This is the code I used to populate the two Lists:

FoodStoreEntities context = new FoodStoreEntities();

List<Supplier> suppliers = context.Suppliers.ToList();
List<Manufacturer> manufacturers = context.Manufacturers.ToList();

This is how I'm trying to add them into an ArrayList:

ArrayList supplierManufacturer = new ArrayList();
foreach (Supplier item in suppliers)
{
    supplierManufacturer.Add(item.vendor);
    supplierManufacturer.Add(item.supplier_email);
}
foreach (Manufacturer item in manufacturers)
{
    supplierManufacturer.Add(item.mfg);
    supplierManufacturer.Add(item.mfgDiscount);
}

However, when I try to display the ArrayList, the types doesn't seem to match. I get "no match" when I run the console:

static void Display(ArrayList aryList)
{
    foreach (Object obj in aryList)
    {
        if (ObjectContext.GetObjectType(obj.GetType()) == typeof(Supplier))
        {
            Supplier supplier = (Supplier)obj;
            Console.WriteLine(supplier.vendor + " " + supplier.supplier_email);
        }
        else if (ObjectContext.GetObjectType(obj.GetType()) == typeof(Manufacturer))
        {
            Manufacturer manufacturer = (Manufacturer)obj;
            Console.WriteLine(manufacturer.mfg + " " + manufacturer.mfgDiscount);
        }
        else
            Console.WriteLine("no match");    
    }
}

I don't know what's going on and have tried searching for related topics but it's to no avail. Please help. Thanks!

kjbartel
  • 10,381
  • 7
  • 45
  • 66
Andrew
  • 23
  • 3
  • Notice that you insert a Supplier.vendor, but expect to get the Supplier. – User1234 Nov 09 '15 at 07:19
  • Run it in a debug mode and use Immediate window http://stackoverflow.com/questions/794255/how-do-you-use-the-immediate-window-in-visual-studio to see what types you get. The key is "Add(item.vendor);" when you are not adding an item itself but it's property. – krtek Nov 09 '15 at 07:20
  • @krtek: It does seem that I am adding its property, and not the item itself. I have changed it to just the item and it works. Thank you for the clarification! – Andrew Nov 09 '15 at 07:28

2 Answers2

0

You could use interface polymorphism. And use mutual properties. And in the foreach loop you use the interface instead of object. And use the properties and methods to display the needed information.

WagoL
  • 97
  • 2
  • 12
0

I found the error. Thanks to krtek. I was adding the item's property instead of the item itself. Changed it to adding them item itself. Fixed :)

Andrew
  • 23
  • 3