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

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

How can I get value from dictionary object?

问题

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

public ActionResult _getprice([FromBody] JsonElement selectedOptionsJson)
{
    var selectedOptions = JsonSerializer.Deserialize<JsonElement>(
        selectedOptionsJson.GetRawText());
    int ProductId = 0;
    var dictionaryOptions = new Dictionary<string, object>();
    foreach (var property in selectedOptions.EnumerateObject())
    {
        dictionaryOptions[property.Name] = GetObjectFromJsonElement(property.Value);
        if (property.Name == "productId")
        {
            ProductId = Convert.ToInt32(GetObjectFromJsonElement(property.Value));
        }
    }     
    var secondDictionary = dictionaryOptions.ElementAtOrDefault(1).Value;
    return Json(1);
}

`seconddictionary` contains: [![Screenshot][1]][1]

[1]: https://i.stack.imgur.com/bCd5F.png

How can I get key value present in `seconddictionary` in `List<keyvalue>` properties key and value?

public class KeyValue
{
    public string Key { get; set; }
    public object Value { get; set; }
}

It is dynamic variant.
英文:

I have a code:

public ActionResult _getprice([FromBody] JsonElement selectedOptionsJson)
{
    var selectedOptions = JsonSerializer.Deserialize&lt;JsonElement&gt;(
        selectedOptionsJson.GetRawText());
    int ProductId = 0;
    var dictionaryOptions = new Dictionary&lt;string, object&gt;();
    foreach (var property in selectedOptions.EnumerateObject())
    {
        dictionaryOptions[property.Name] = GetObjectFromJsonElement(property.Value);
        if (property.Name == &quot;productId&quot;)
        {
            ProductId = Convert.ToInt32(GetObjectFromJsonElement(property.Value));
        }
    }     
    var secondDictionary = dictionaryOptions.ElementAtOrDefault(1).Value;
    return Json(1);
}

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

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

public class KeyValue
{
    public string Key { get; set; }
    public object Value { get; set; }
}

It is dynamic variant.

答案1

得分: 3

你可以使用Linq来实现:

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

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

英文:

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

List&lt;KeyValue&gt; keyValueList = dict.Select(kvp =&gt; new KeyValue{
Key = kvp.Key,
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:

确定