Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, everyone. I am working on a c# application where I have about 15 methods that Update entries in the database. So I want to make one method for update with two parameters: Dictionary<int, object> dictionary and string tableName. The 'object' part of the dictionary will accept different ViewModels. Here is my code:

C#
public void UpdateEntriesFromAGivenTable(Dictionary<int, object> dictionary, string tableName)
        {
            foreach (KeyValuePair<int, object> entry in dictionary)
            {
                Dictionary<string, object> dict = GetTypeNamesAndValuesWithReflection(entry.Value);

                foreach (var item in dict)
                {
                    if (item.Value != null && (!string.Equals(item.Key, "id")))
                    {
                        UpdateEntry(tableName, item.Key, item.Value, entry.Key);
                    }
                }
            }
        }


But when I tried to use the above method, I receive the red underline below the parameter "Dictionary<int, user>" and the error message is: cannot convert from 'System.Collections.Generic.Dictionary<int, Models.User> to 'System.Collections.Generic.Dictionary<int, object>.

What I have tried:

I tried the following cast:

(Dictionary<int, object>)(users)

but without success. I looked for help in google and stackoverflow but did not find a similar issue. So can you tell me is it possible to cast a variable of Type: Dictionary<int, Models.User> to Dictionary<int, object> and if the answer is yes, how to do it? Thanks.
Posted
Updated 27-Sep-18 2:31am
v2

Use generics

public void UpdateEntriesFromAGivenTable<T>(Dictionary<int, T> dictionary, string tableName)
{
    foreach (KeyValuePair<int, T> entry in dictionary)
    {
        Dictionary<string, object> dict = GetTypeNamesAndValuesWithReflection(entry.Value);

        foreach (var item in dict)
        {
            if (item.Value != null && (!string.Equals(item.Key, "id")))
            {
                UpdateEntry(tableName, item.Key, item.Value, entry.Key);
            }
        }
    }
}


You can call it like

Dictionary<int, User> d = new Dictionary<int, User>();

d.Add(1, new User { Name = "A" });
d.Add(2, new User { Name = "B" });

UpdateEntriesFromAGivenTable(d, "");
 
Share this answer
 
Comments
Member 13992723 27-Sep-18 9:06am    
Thank you, I tested your solution and it works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900