我需要一些帮助来开发一种算法,该算法基于匹配的键/值对来合并列表列表。
在下面的示例中,我有3个List>我想使用Merge方法调用减少/合并的实例。 Merge的对象是获取包含任何匹配键/值对的实例,并将两个列表合并到包含两个列表中所有对的新列表中。因此,在此示例中,Merge方法应将3个列表压缩为1,因为list1和list2都包含匹配的键名和“key1”和“key2”的值。然后list1和list2的新合并列表将进一步与list3合并,因为它们都包含匹配的键名和“key4”的值。
任何人对高效算法都有任何想法?我目前正在使用一种非常慢的递归方法,因为它将每个列表与每个其他列表进行比较。
var list1 = new List<KeyValuePair<string, string>> {
new KeyValuePair<string,string>("key1","2"),
new KeyValuePair<string,string>("key2","5"),
new KeyValuePair<string,string>("key3","20")
};
var list2 = new List<KeyValuePair<string, string>> {
new KeyValuePair<string,string>("key1","2"),
new KeyValuePair<string,string>("key2","5"),
new KeyValuePair<string,string>("key4","10"),
new KeyValuePair<string,string>("key5","A"),
new KeyValuePair<string,string>("key6","B"),
new KeyValuePair<string,string>("key7","C")
};
var list3 = new List<KeyValuePair<string, string>> {
new KeyValuePair<string,string>("key10","2"),
new KeyValuePair<string,string>("key20","5"),
new KeyValuePair<string,string>("key4","10"),
new KeyValuePair<string,string>("key40","2")
};
var fullList = new List<IList<KeyValuePair<string, string>>>();
fullList.Add(list1);
fullList.Add(list2);
fullList.Add(list3);
List<IList<KeyValuePair<string, string>>> mergedList = fullList.Merge();
/*
output should be a single a single IList<KeyValuePair<string, string>> with a count of 10 KeyValuePair<string,string> items
mergedList would contain the following key/value pairs
"key1","2"
"key2","5"
"key3","20"
"key4","10"
"key5","A"
"key6","B"
"key7","C"
"key10","2"
"key20","5"
"key40","2"
*/
答案 0 :(得分:2)
请参阅linq set operators http://geekswithblogs.net/BlackRabbitCoder/archive/2011/05/05/c.net-little-wonders-the-linq-set-operations----theyre-not.aspx
上的这篇文章答案 1 :(得分:0)
看起来您可以使用Dictionary<String, HashSet<String>>
来存储合并的数据。这将允许您快速查找输出是否已包含所需的键,如果不是,则添加它(并且,对于它的值,包含当前项的值的哈希集)。如果密钥已经存在于字典中,只需获取值(一个哈希集)并调用它的Add方法,该方法已经有效地防止了重复。
答案 2 :(得分:0)
听起来你想要从你的描述中结合三个列表而不是获得一个列表列表,例如。
var list1 = new List<KeyValuePair<string, string>> {
new KeyValuePair<string,string>("key1","2"),
new KeyValuePair<string,string>("key2","5"),
new KeyValuePair<string,string>("key3","20")
};
var list2 = new List<KeyValuePair<string, string>> {
new KeyValuePair<string,string>("key1","2"),
new KeyValuePair<string,string>("key2","5"),
new KeyValuePair<string,string>("key4","10"),
new KeyValuePair<string,string>("key5","A"),
new KeyValuePair<string,string>("key6","B"),
new KeyValuePair<string,string>("key7","C")
};
var list3 = new List<KeyValuePair<string, string>> {
new KeyValuePair<string,string>("key10","2"),
new KeyValuePair<string,string>("key20","5"),
new KeyValuePair<string,string>("key4","10"),
new KeyValuePair<string,string>("key40","2")
};
var unionedList = new List<KeyValuePair<string, string>>();
unionedList.AddRange(list1.Union(list2).Union(list3));
foreach (var kvp in unionedList)
{
Console.WriteLine(string.Format("{0} {1}", kvp.Key, kvp.Value));
}
unionedList现在将根据您的预期输出包含不同的KeyValue对列表。如果值不同,您将获得重复的密钥。