gpt4 book ai didi

c# - 要区分的 KeyValuePair 列表

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:58 24 4
gpt4 key购买 nike

我有一个 KeyValuePair 列表,它的值也列在列表中,例如

List<KeyValuePair<string, List<string>>> ListX = new List<KeyValuePair<string,List<string>>>();
ListX.Add(new KeyValuePair<string,List<string>>("a",list1));
ListX.Add(new KeyValuePair<string,List<string>>("b",list1));
ListX.Add(new KeyValuePair<string,List<string>>("a",list1));`

我希望列表中每个KeyValuePair的键不重复,只有键,我可以在这个列表中使用Distinct吗?

例如,我希望删除列表中具有“a”键的第三项,因为它是重复的。

最佳答案

虽然可以解决当前的 List使其具有Distinct键,我认为适合您情况的最简单的解决方案是使用 Dictionary<string,List<string>>

完全满足您的需求:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
dict.Add("a", new List<string>());
dict.Add("b", new List<string>());
dict.Add("a", new List<string>()); //will throw an error

图片:

enter image description here

如果你需要检查一个Key当您要添加 <Key,Value> 时已经存在到你的字典,只需通过ContainsKey检查:

if (dict.ContainsKey(key)) //the key exists

关于c# - 要区分的 KeyValuePair 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763842/

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