gpt4 book ai didi

c# - 有效地合并列表列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:53:22 24 4
gpt4 key购买 nike

我需要一些帮助来开发一种算法,该算法基于键/值对等匹配来合并列表的列表。

在下面的示例中,我有 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"
*/

最佳答案

关于c# - 有效地合并列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7207414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com