我有兩個類:查詢嵌套列表
public GeneralClassName
{
public GeneralClassName()
{
SpecificList = new List<OtherClass>();
}
public string StringValue;
public string OtherStringValue;
public List<OtherClass> SpecificList;
}
和
public OtherClass
{
public string Name;
public string Number;
}
一個JSON反序列化我得到一個不錯List<GeneralClassName>
後,結果我要的是一個Dictionary<string, int>
,其值是的總和List<GeneralClassName>
內的List<OtherClass>
內的變數「數字」,而關鍵是變數名稱。
換句話說,我想按名稱對數字進行分組。現在
,跨我的腦海裏傳來的唯一事情是一個嵌套的foreach,這樣的事情:
Dictionary<string, int> resultDictionary = new Dictionary<string, int>();
foreach(List<OtherClass> listOtherClass in bigListGeneralClass.Select(x => x.SpecificList))
{
foreach(OtherClass otherClass in listOtherClass)
{
int value = 0;
if(resultDictionary.ContainsKey(otherClass.Name))
{
resultDictionary[otherClass.Name] += otherClass.Number;
}
else
{
resultDictionary.Add(otherClass.Name, otherClass.Number);
}
}
}
雖然這種解決方案似乎運作良好,我不喜歡它。 有沒有更簡潔的方法來找到這個結果?也許通過一個不錯的LINQ查詢?
什麼otherClass.count?你的意思是otherClass.Number? –
當我第一次寫這個問題時,我使用了一個不同的變量名。然後在閱讀文本時,我發現使用「計數」令人困惑。你發現的那個必須滑倒:|對於錯誤感謝,並感謝編輯。 – Abaco