Home > Back-end >  Replace property values in a class from List<Dictionary> values
Replace property values in a class from List<Dictionary> values

Time:09-29

I have a method that takes a List<Dictionary<string,object>> as a parameter. The plan is to use that parameter, but only update the values held in a particular class. Here is the (partially written) method

    public async Task<Errors> UpdatePageForProject(Guid projectId, List<Dictionary<string, object>> data)
    {
        if (!IsValidUserIdForProject(projectId))
            return new Errors { ErrorMessage = "Project does not exist", Success = false };

        if (data.Count == 0)
            return new Errors { ErrorMessage = "No data passed to change", Success = false };

        var page = await _context.FlowPages.FirstOrDefaultAsync(t => t.ProjectId == projectId);
        foreach (var d in data)
        {
            
        }

        return new Errors { Success = true };
    }

My original plan is to take each dictionary, check if the key and the property in page match and then alter the value (so I can pass in 1 dictionary or 8 dictionaries in the list and then alter page to save back to my entity database).

I'd rather not use reflection due to the speed hit (though C#9 is really fast, I'd still rather not use it), but I'm not sure how else this can be done. I did consider using AutoMapper to do this, but for now would rather not (it's a PoC, so it is possibly overkill)

CodePudding user response:

If you want to do this without Reflection (which I agree is a good idea, not just for performance reasons) then you could use a "map" or lookup table with actions for each property.

var map = new Dictionary<string,Action<Page,object>>()
{
     { "Title",   (p,o) => p.Title       = (string)o   },
     { "Header",  (p,o) => p.Field1      = (string)o   },
     { "DOB",     (p,o) => p.DateOfBirth = (DateTime)o }
};

You can then iterate over your list of dictionaries and use the map to execute actions that update the page.

foreach (var dictionary in data)
{
    foreach (entry in dictionary)
    {
        var action = map[entry.Key];
        action(page, entry.Value);
    }
}
  • Related