如何从字典对象中获取值?

huangapple go评论107阅读模式
英文:

How can I get value from dictionary object?

问题

以下是您要翻译的代码部分:

  1. public ActionResult _getprice([FromBody] JsonElement selectedOptionsJson)
  2. {
  3. var selectedOptions = JsonSerializer.Deserialize<JsonElement>(
  4. selectedOptionsJson.GetRawText());
  5. int ProductId = 0;
  6. var dictionaryOptions = new Dictionary<string, object>();
  7. foreach (var property in selectedOptions.EnumerateObject())
  8. {
  9. dictionaryOptions[property.Name] = GetObjectFromJsonElement(property.Value);
  10. if (property.Name == "productId")
  11. {
  12. ProductId = Convert.ToInt32(GetObjectFromJsonElement(property.Value));
  13. }
  14. }
  15. var secondDictionary = dictionaryOptions.ElementAtOrDefault(1).Value;
  16. return Json(1);
  17. }
  18. `seconddictionary` contains: [![Screenshot][1]][1]
  19. [1]: https://i.stack.imgur.com/bCd5F.png
  20. How can I get key value present in `seconddictionary` in `List<keyvalue>` properties key and value?
  21. public class KeyValue
  22. {
  23. public string Key { get; set; }
  24. public object Value { get; set; }
  25. }
  26. It is dynamic variant.
英文:

I have a code:

  1. public ActionResult _getprice([FromBody] JsonElement selectedOptionsJson)
  2. {
  3. var selectedOptions = JsonSerializer.Deserialize&lt;JsonElement&gt;(
  4. selectedOptionsJson.GetRawText());
  5. int ProductId = 0;
  6. var dictionaryOptions = new Dictionary&lt;string, object&gt;();
  7. foreach (var property in selectedOptions.EnumerateObject())
  8. {
  9. dictionaryOptions[property.Name] = GetObjectFromJsonElement(property.Value);
  10. if (property.Name == &quot;productId&quot;)
  11. {
  12. ProductId = Convert.ToInt32(GetObjectFromJsonElement(property.Value));
  13. }
  14. }
  15. var secondDictionary = dictionaryOptions.ElementAtOrDefault(1).Value;
  16. return Json(1);
  17. }

seconddictionary contains: 如何从字典对象中获取值?

How can I get key value present in seconddictionary in List&lt;keyvalue&gt; properties key and value?

  1. public class KeyValue
  2. {
  3. public string Key { get; set; }
  4. public object Value { get; set; }
  5. }

It is dynamic variant.

答案1

得分: 3

你可以使用Linq来实现:

  1. List<KeyValue> keyValueList = dict.Select(kvp => new KeyValue{
  2. Key = kvp.Key,
  3. Value = kvp.Value}).ToList();

这样你应该得到一个包含字典中所有对象的列表。

英文:

If I understand correctly what you need. You can use Linq to do so:

  1. List&lt;KeyValue&gt; keyValueList = dict.Select(kvp =&gt; new KeyValue{
  2. Key = kvp.Key,
  3. Value = kvp.Value}).ToList();

You should have a list with every objects in your dictionary.

huangapple
  • 本文由 发表于 2023年7月20日 19:41:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76729481.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定