[英]how to check key existence for dictionary within a dictionary in C#
在下面的代碼中,如何檢查字典中字典的鍵是否存在?
當前執行拋出鍵存在錯誤。
輸出,對於鍵“ a”,另一個鍵“ X”的值分別為1和2
我們為此有更好的收藏嗎?
var data = new Dictionary<string, Dictionary<string, object>>();
foreach (var j in GetTopData())
{
foreach (var p in BottomData())
{
if (data.Keys.Contains(j.ToString()))
{
data[j].Add(p.Name, p.Value);
}
else
{
data.Add(j, new Dictionary<string, object> { { p.Name, p.Value } });
}
}
}
這是數據類,
private static List<TempData> BottomData()
{
return new List<TempData>
{
new TempData{ Name="X", Value=1},
new TempData{ Name="X", Value=2}
};
}
private static List<string> GetTopData()
{
return new List<string> { "a"};
}
public class TempData
{
public string Name { get; set; }
public object Value { get; set; }
}
您的代碼可以簡化為:
var data = new Dictionary<string, Dictionary<string, List<object>>>();
foreach (var j in GetTopData())
{
foreach (var p in BottomData())
{
Dictionary<string, List<object>> values;
var existed = data.TryGetValue(j, out values);
if (!existed)
values = new Dictionary<string, List<object>>();
List<Object> list;
var existed2 = values.TryGetValue(p.Name, out list);
if (!existed2)
list = new List<object>();
list.Add(p.Value);
if (!existed)
data.Add(j, values);
if (!existed2)
values.Add(p.Name, list);
}
}
您需要檢查兩個字典中的現有數據。 目前,您只在檢查一本字典中的存在性:
var data = new Dictionary<string, Dictionary<string, object>>();
foreach (var j in GetTopData())
{
foreach (var p in BottomData())
{
if(data.ContainsKey(j.ToString()))
{
var mydict = data[j.ToString()];
if (!mydict.ContainsKey(p.Name))
data[j].Add(p.Name, p.Value);
}
else
{
data.Add(j, new Dictionary<string, object> { { p.Name, p.Value } });
}
}
}
因為您需要一個鍵來包含多個值,所以Dictionary<string, Dictionary<string, object>>
對您不起作用(特定鍵只允許使用1個值)。 您可以使用Dictionary<string, Dictionary<string, List<object>>>
,但是它很難閱讀且難以使用。 因此,我覺得最好使用Dictionary,將兩個鍵組合為一個,如CombinedKey類中所示(在C#7.0中, ValueTuple<string, string>
也可以使用):
public class CombinedKey
{
public string Key1;
public string Key2;
// It is necessary to override Equals and GetHashCode to make
// it work properly as a dictionary key.
public override bool Equals(object obj)
{
var otherCombinedKey = obj as CombinedKey;
return otherCombinedKey != null
&& otherCombinedKey.Key1 == this.Key1
&& otherCombinedKey.Key2 == this.Key2;
}
public override int GetHashCode()
{
return Key1.GetHashCode() ^ Key2.GetHashCode();
}
}
然后以這種方式使用它:
Dictionary<CombinedKey, List<object>> data = new Dictionary<CombinedKey, List<object>>();
foreach (var j in GetTopData())
{
foreach (var p in BottomData())
{
var key = new CombinedKey() { Key1 = j, Key2 = p.Name };
List<object> list;
if(!data.TryGetValue(key, out list))
{
data[key] = list = new List<object>();
}
list.Add(p.Value);
}
}
如果您的數據是不可變的,則還可以使用Lookup<CombinedKey, object>
類。
回答您的問題, 如何在C#中檢查字典中字典的鍵是否存在 :
您可以使用Linq進行檢查,例如以下示例 :
bool keyExistance = data.Any(x=>x.Value.ContainsKey(keyTocheck));
但是在此之前,您必須修復代碼中的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.