如何检查 List<Dictionary<string, string>> 类型的对象以根据字典中的另一个值设置一个值?

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

我有一个名为 reportData 的对象,它保存着一份报告的数据。 这个对象是类型 List<Dictionary<string, string>> 我需要添加逻辑来操作 reportData,当键 "Type" 的值是 Withdrawal 时,键 "TransAmount" 的值前面应该有一个减号。 我在想我可以用一些 linq 来完成这个,但我没有成功。

这是我到目前为止尝试过的...

        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
            )
        }

这里是保存在 reportData 中的数据的快照。列表中显示的项目是类型 "Withdrawal",我的代码需要处理列表中类型为 "Deposit"

的项目

https://gyazo.com/a5183aa404e51672712d680dcd8ad6af

这样的事情怎么样?

foreach (var dict in reportData)
        {
            var keys = new List<string>(dict.Keys);
            foreach (string key in keys)
            {
                if (key == "Type")
                {
                    if (dict[key] == "Deposit")
                    {
                        dict["TransAmount"] =   "-" +dict["TransAmount"] ;
                    }
                }
            }
        }

试试这个https://dotnetfiddle.net/Ii0MR7

我们只需要一个循环和一个操作。 我们一个接一个地使用字典,在每个字典中我们正在寻找特定的键 "Type",同时试图将其值赋给名为 type 的变量(这正是 TryGetValue 所做的).如果元素存在,它也会 returns true 。此时我们只需要确定它的值就是我们要找的那个即可。 如果是 - 我们进入代码块并修改另一个值。如果您不熟悉 $ 字符串插值,请查看 this 文章。

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"]}";
   }
}

是的,您可以使用 LINQ 来完成,但不推荐这样做,LINQ 的一个很好的用例是数据查询,而对于操作数据,最好使用良好的旧循环,不过这里是代码:

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>