我有一個看起來像這樣的類
public class VegetablesPriceNode
{
public string Country{get;set;}
public Dictionary<string,string> VegetableDictionary{get;set;}
}
然后我以串列的形式獲取每個單獨的蔬菜價格節點
List<VegetablesPriceNode> = //I get this object after parsing.
所有蔬菜字典中都有相同的鍵,但對于不同的國家/地區,我需要水平顯示。
Veggies Afghanistan. Bahrain
-------------------------------------------------------------------------
Onions | $2.00 | $1.00 ....
Potatoes| $3.00 | $1.50 ....
.......
public static void Main()
{
// I get a List<VegetablesPriceNode> from some place
// Need to extract all values for the same key from all dictionaries
// I tried to extract all keys first using
var = vegetablesPriceNodeList.SelectMany(x => x.VegetableDictionary.Select(x => x.Key)).ToHashSet();
// I chose HashSet because all keys were getting appended and there is no unique.
}
如何在所有國家/地區的所有字典中提取相同的關鍵資訊?例如,我想要所有國家的所有洋蔥價格。所以遍歷所有的洋蔥字典作為鍵并獲取它們的值?
上述先提取鍵然后獲取該鍵的所有值的方法是否理想?還是有更好的解決方案?
由于我使用 DataTable 來存盤此資訊,因此 DataTable 使用 object[] 我得到的物件是 List
預期:看起來像的字串值串列
"Onions","$2.00","$3.00"
樣本資料:
[{"Country":"Afghanistan","VegetableDictionary":{"Onions":"$1.00","Potatoes":"$1.40"}},{"Country":"Bahrain","VegetableDictionary":{"Onions":"$3.00","Potatoes":"$3.40"}}]
uj5u.com熱心網友回復:
我不知道你想要的輸出到底是什么。
我相信類似的東西:
[["Onions","$1.00","$3.00"],["Potatoes","$1.40","$3.40"]]
我做了一個例子,我希望它對你的用例有用:
https://dotnetfiddle.net/RPFZen
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
public class VegetablesPriceNode
{
public string Country { get; set; }
public Dictionary<string, string> VegetableDictionary { get; set; }
}
public class Program
{
public static void Main()
{
var json = "[{\"Country\":\"Afghanistan\",\"VegetableDictionary\":{\"Onions\":\"$1.00\",\"Potatoes\":\"$1.40\"}},{\"Country\":\"Bahrain\",\"VegetableDictionary\":{\"Onions\":\"$3.00\",\"Potatoes\":\"$3.40\"}}]";
var vegetablesPriceNodeList = JsonConvert.DeserializeObject<List<VegetablesPriceNode>>(json);
var obj = vegetablesPriceNodeList
.SelectMany(x =>
x.VegetableDictionary
.Select(x => x.Key)
)
.Distinct()
.Select((k) =>
vegetablesPriceNodeList
.Select(v => v.VegetableDictionary[k])
.Prepend(k)
.ToArray()
).ToArray();
var output = JsonConvert.SerializeObject(obj);
Console.WriteLine(output);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429166.html
上一篇:如何在python中多次回圈
下一篇:c#和python中解碼的不同值
