Search code examples
c#dto

How to check an object of type List<Dictionary<string, string>> to set one value based off another value in the dictionary?


I have an object called reportData, which is holding the data for a report. This object is of type List<Dictionary<string, string>> I need to add logic to manipulate reportData that when the value of the key "Type" is Withdrawal the value of the key "TransAmount" should have a minus sign before it. I was thinking I can accomplish this with some linq but I am not having any success.

This is what I tried so far...

        foreach (var kvp in reportData.SelectMany(m => m).Where(x => x.Value != null))
        {
            if (kvp.Value.Equals("Deposit"))
                (
            //Over here I need to set the value of the key "TransAmount" to have a minus sign before it, but I'm not sure how to go about it
            )
        }

Over here is a snapshot of the data that is being held in reportData. The showcased item in the list is of Type "Withdrawal", My code needs to deal with items in the list that are of Type "Deposit"

https://gyazo.com/a5183aa404e51672712d680dcd8ad6af


Solution

  • We only need one loop and one operation. We take dictionaries one by one, in each dictionary we are looking for the specific key "Type" while at the same time trying to get its value to variable called type (that's precisely what TryGetValue does). It also returns true in case when element exists. At this point we only need to make sure that the value of it is the one we're looking for. If yes - we get in to the code block and modify another value. If you're not familiar with $ string interpolation please check this article.

    foreach (var dict in reportData)
    {
       if (dict.TryGetValue("Type", out var type)
           && type == "Withdrawal"
           && dict.TryGetValue("TransAmount", out var amt)
           && !string.IsNullOrEmpty(amt))
       {
           dict["TransAmount"] = $"-{dict["TransAmount"]}";
       }
    }
    

    And yes you can do it with LINQ but it is not recommended, a good use-case for LINQ is data querying and for manipulating data it is better to use good old loops, nevertheless here is the code:

    reportData = reportData.Select(d =>
    {
       if (d.TryGetValue("Type", out var type) && type == "Withdrawal")
       {
           d["TransAmount"] = $"-{d["TransAmount"]}";
       }
       return d;
    }.ToList(); // this will create a new instance of List<Dictionary>