Search code examples
c#dictionaryobjectasp.net-coredynamicobject

Cannot convert from custom object to object or dynamic


I have a List which I would like to populate with different types of objects, trying to do it with object\dynamic, but it doesn't, even when casting. using asp.net core. See my code:

public Dictionary<string, Employee> getEmployees(); //This method returns a dictionary of string as a key and Employee as a value.
public Dictionary<string, customer>()> getCustomers(); //same principal


public List<Dictionary<string, object>> getDifferentItems()
{
   List<Dictionary<string, object>> listOfItems = new List<Dictionary<string, object>>();
   listOfItems.add(getEmployees()); //Error
   listOfItems.add(getCustomers()); //Error
   return listOfItems;
}

Solution

  • Depending on what you are trying to do, I can see two solutions:

    Create a list of TWO different dictionaries

        public Dictionary<string, Employee> getEmployees() {
            return new Dictionary<string, Employee>();
        }
        public Dictionary<string, Customer> getCustomers() {
            return new Dictionary<string, Customer>();
        }
    
    
        public List<Dictionary<string, object>> getDifferentItems()
        {
            List<Dictionary<string, object>> listOfItems = new List<Dictionary<string, object>>();
            listOfItems.Add(this.getEmployees().ToDictionary(entry => (string)entry.Key,
                      entry => (object)entry.Value)); 
            listOfItems.Add(this.getCustomers().ToDictionary(entry => (string)entry.Key,
                      entry => (object)entry.Value)); 
            return listOfItems;
        }
    

    Create one dictionary with all the values

        public Dictionary<string, Employee> getEmployees() {
            return new Dictionary<string, Employee>();
        }
        public Dictionary<string, Customer> getCustomers() {
            return new Dictionary<string, Customer>();
        }
    
    
        public Dictionary<string, object> getDifferentItems()
        {
            Dictionary<string, object> listOfItems = new Dictionary<string, object>();
            foreach (var entry in getEmployees()) {
                listOfItems.Add(entry.Key, entry.Value);
            }
            foreach (var entry in getCustomers()) {
                listOfItems.Add(entry.Key, entry.Value);
            }
            return listOfItems;
        }