C#实现对于一字典列表List<dictionary<string,string>>,如果字典b的值等于字典a的键,那么称b为a的祖字典,b为a的后字典。字典a的祖字典的祖字典也是a的祖字典。设一字典的键为string,求其所有的祖字典列表。
时间: 2023-12-29 14:24:20 浏览: 158
C#简单的通用基础字典实现方法
以下是C#实现对于一字典列表List<dictionary<string,string>>,求其所有的祖字典列表的代码:
```csharp
// 定义一个函数,用于获取指定字典的所有祖字典
public static List<Dictionary<string, string>> GetAncestorDictionaries(Dictionary<string, string> dict, List<Dictionary<string, string>> dictList)
{
List<Dictionary<string, string>> ancestorDicts = new List<Dictionary<string, string>>();
foreach (Dictionary<string, string> d in dictList)
{
if (d == dict) // 如果是自己,跳过
{
continue;
}
if (d.ContainsKey(dict.Values.First())) // 如果值等于当前字典的键
{
ancestorDicts.Add(d); // 添加到祖字典列表中
ancestorDicts.AddRange(GetAncestorDictionaries(d, dictList)); // 递归获取祖字典的祖字典
}
}
return ancestorDicts;
}
// 测试代码
List<Dictionary<string, string>> dictList = new List<Dictionary<string, string>>();
Dictionary<string, string> a = new Dictionary<string, string>();
a.Add("key1", "value1");
a.Add("key2", "value2");
a.Add("key3", "value3");
Dictionary<string, string> b = new Dictionary<string, string>();
b.Add("key4", "value1");
b.Add("key5", "value2");
b.Add("key6", "value3");
Dictionary<string, string> c = new Dictionary<string, string>();
c.Add("key7", "value1");
c.Add("key8", "value2");
c.Add("key9", "value3");
dictList.Add(a);
dictList.Add(b);
dictList.Add(c);
List<Dictionary<string, string>> ancestorDicts = GetAncestorDictionaries(a, dictList);
foreach (Dictionary<string, string> d in ancestorDicts)
{
Console.WriteLine(d.ToString());
}
```
阅读全文