110,534
社区成员
发帖
与我相关
我的任务
分享
public class MyDict<TKey, TValue> : Dictionary<TKey, List<TValue>>
{
public void Add(TKey key, TValue value)
{
var x = new List<TValue>();
if (this.TryGetValue(key, out x))
{
x.Add(value);
}
else
{
x = new List<TValue>() { value};
base.Add(key, x);
}
}
}
static List<string> Get(string str)
{
var p = new Dictionary<int,int>();
var res = new List<string>();
var buf = new List<string>();
if (data.ContainsKey(str)) buf.AddRange(data[str]);
for(var i=0; i<buf.Count; i++)
{
if (buf[i] != str && res.IndexOf(buf[i]) < 0)
{
res.Add(buf[i]);
if (data.ContainsKey(buf[i])) buf.AddRange(data[buf[i]]);
}
}
return res;
}
public static MyDict<string, string> data;
static void Main(string[] args)
{
data = new MyDict<string, string>();
data.Add("a", "b");
data.Add("a", "c");
data.Add("a", "d");
data.Add("d", "f");
data.Add("d", "b");
data.Add("f", "c");
data.Add("f", "a");
data.Add("b", "a");
data.Add("b", "c");
data.Add("c", "v");
data.Add("c", "b");
data.Add("v", "s");
data.Add("h", "j");
Console.WriteLine(string.Join(",", Get("a")));
Console.ReadKey();
}
static List<string> Test(string str)
{
List<KeyValuePair<string, string>> sourceList = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("a", "b"),
new KeyValuePair<string, string>("a", "c"),
new KeyValuePair<string, string>("a", "d"),
new KeyValuePair<string, string>("d", "f"),
new KeyValuePair<string, string>("d", "b"),
new KeyValuePair<string, string>("f", "c"),
new KeyValuePair<string, string>("f", "a"),
new KeyValuePair<string, string>("b", "a"),
new KeyValuePair<string, string>("b", "c"),
new KeyValuePair<string, string>("c", "v"),
new KeyValuePair<string, string>("c", "b"),
new KeyValuePair<string, string>("v", "s"),
new KeyValuePair<string, string>("h", "j")
};
List<string> resultList = new List<string>();
LoopSourceList(str, sourceList, resultList);
return resultList;
}
static void LoopSourceList(string key, List<KeyValuePair<string, string>> sourceList, List<string> resultList)
{
var query = sourceList.Where(kv => kv.Key == key).ToList();
if (query.Count > 0)
{
foreach (var kv in query)
{
if (!resultList.Contains(kv.Value))
{
resultList.Add(kv.Value);
LoopSourceList(kv.Value, sourceList, resultList);
}
}
}
}
不知道你的例子为啥会有自己…… Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("a", "b");
data.Add("a", "c");
你确认你的例子正确?这不错到家了么,运行直接异常的货啊