要求去重的键值对列表

3

我有一个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”键的列表中的第三个项目,因为它是重复的。

3
请使用Dictionary<string,List<string>>代替。如果已存在相同的键,则添加方法将抛出异常。您可以首先使用ContainsKey方法检查键是否已经存在,或者您可以使用索引器来替代Add方法,如果键已经存在,则会覆盖旧值。例如:dic["a"] = list1; - M.kazem Akhgary
5个回答

3

虽然可以通过调整当前的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

图片:

在此输入图像描述

如果您想要向字典中添加一个<Key,Value>,并且需要检查是否已经存在该Key,只需通过ContainsKey进行检查:

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

1
这个很好用,我之前不知道字典可以有多个条目。谢谢。 - user1947393

3
var dictionaryX = ListX
    .GroupBy(x => x.Key, (x, ys) => ys.First())
    .ToDictionary(x => x.Key, x => x.Value);

我不确定这是否是您要寻找的内容,但这是一个查询,它将通过仅获取每个重复键的第一个值,将ListX转换为字典。


0

你可以使用

Dictionary<TKey, TValue>   

Tkey 和 Tvalue 是通用数据类型。

例如,它们可以是 int、string、另一个字典等。

示例:Dictionary<int, string>, Dictionary<int, List<employee>> 等。

在所有这些情况下,键是不同的部分,即不能再次插入相同的键。

您可以使用 Distinct 检查键是否存在,这样即使尝试添加相同的键也不会出现异常。

然而,Distinct 仅能防止相同的键值对

防止添加相同的键,请使用 Enumerable.GroupBy
ListItems.Select(item => { long value; bool parseSuccess = long.TryParse(item.Key, out value); return new { Key = value, parseSuccess, item.Value }; }) .Where(parsed => parsed.parseSuccess) .GroupBy(o => o.Key) .ToDictionary(e => e.Key, e => e.First().Value)


这段代码将把第一个"a"作为键添加到列表中。您不能将相同的键"a"添加到字典中,这也是添加字典的唯一目的。 - DAre G

0
List<Dictionary<int, List<int>>> list = new List<Dictionary<int, List<int>>>(); //List with a dictinary that contains a list 
int key = Convert.ToInt32(Console.ReadLine()); // Key that you want to check if it exist in the dictinary
int temp_counter = 0; 

foreach(Dictionary<Int32,List<int>> dict in list)
{
    if(dict.ContainsKey(key))
    temp_counter+=temp_counter;
}

if (temp_counter == 0) // key not present in dictinary then add a to the list a dictinary object that contains your list
{
    Dictionary<int,List<int>> a = new Dictionary<int,List<int>>();
    a.Add(key,new List<int>()); // will contain your list
    list.Add(a);
}

检查一下这个是否可行


0
你可以使用类 Dictionary<TKey, TValue>,它继承自 IEnumerable<KeyValuePair<TKey, TValue>>。它是一个 KeyValuePairs 集合,只允许唯一的键。

如果我尝试添加重复的键,它会给我一个错误,对吧?我不想出现错误,我希望它在不出现错误的情况下阻止添加。 - user1947393
@user1947393 在插入项之前添加一个检查 if(!d.ContainsKey(key)) - Ivan Gritsenko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接