【问题标题】:How to check an object of type List<Dictionary<string, string>> to set one value based off another value in the dictionary?如何检查 List<Dictionary<string, string>> 类型的对象以根据字典中的另一个值设置一个值?
【发布时间】:2019-08-14 17:24:18
【问题描述】:

我有一个名为 reportData 的对象,它保存报告的数据。 这个对象是类型 List&lt;Dictionary&lt;string, string&gt;&gt; 我需要添加逻辑来操作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 中保存的数据的快照。列表中展示的项目属于“提款”类型,我的代码需要处理列表中属于“存款”类型的项目

https://gyazo.com/a5183aa404e51672712d680dcd8ad6af

【问题讨论】:

    标签: c# dto


    【解决方案1】:

    这样的事情怎么样?

    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

    【讨论】:

      【解决方案2】:

      我们只需要一个循环和一个操作。 我们一一获取字典,在每个字典中我们都在寻找特定的键“类型”,同时试图将其值传递给名为 type 的变量(这正是 TryGetValue 所做的)。如果元素存在,它还会返回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>
      

      【讨论】:

      • 非常感谢您提供这个出色的解决方案!你能解释一下第一种方法吗,我想确保我理解正确。
      • 谢谢。在某些情况下 TransAmount 可以为空,因此我需要检查它是否为空。这有意义吗? if (dict.TryGetValue("Type", out var type) && type == "Withdrawal") { if (dict.TryGetValue("TransAmount", out var TransAmount)) dict["TransAmount"] = $"-{dict ["交易金额"]}"; }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2012-01-20
      • 2018-12-30
      相关资源
      最近更新 更多