I need a little assistance developing an algorithm that merges Lists of Lists based on matching like key/value pairs.
In the example below I have 3 List> instances which I would like to reduce/merge using a Merge method call. The object of the Merge is to take instances that contain any matching key/value pair and merge both lists into a new list containing all of the pairs from both lists. So in this example the Merge method should condense the 3 lists into 1 because list1 and list2 both containing matching key names and values for “key1” and “key2”. Then the new merged list of list1 and list2 would further merge with list3 because they both contain matching key names and values for “key4”.
Anyone have any ideas on an efficient algorithm? I’m currently using a recursive method that is extremely slow as it compares every list to every other list.
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"
*/
See this post on linq set operators http://geekswithblogs.net/BlackRabbitCoder/archive/2011/05/05/c.net-little-wonders-the-linq-set-operations—-theyre-not.aspx