如何从 C# 中的字典中的特定位置删除元素?

4 c# hash dictionary element

我有一个“字典”数据库,我想从特定位置返回一个元素。我看到有“ElementAt”功能,但我没有设法使用它。

为什么这样的事情不起作用?

closeHash.ElementAt<State>(i);
Run Code Online (Sandbox Code Playgroud)

它告诉我以下错误:

错误 3 'System.Collections.Generic.Dictionary' 不包含 'ElementAt' 的定义,并且最佳扩展方法重载 'System.Linq.Queryable.ElementAt(System.Linq.IQueryable, int)' 有一些无效参数

这段代码也不起作用,因为 closeHash[i] 只给我索引而不是实际元素:

   if (closeHash.ContainsKey(i) && ((State)closeHash[i]).getH() + 
((State)closeHash[i]).getG() > checkState.getH() + checkState.getG()
Run Code Online (Sandbox Code Playgroud)

Dictionary 中的每个元素都属于“State”类,而 checkState 也是具有 GetH 和 GetG 函数的 State。我想取出第 I 个位置的元素并对其进行处理,而不仅仅是将其删除。

提前致谢!

格雷格

Luc*_*s B 7

使用 Remove 函数并传入 ElementAt 怎么样?

        Dictionary<int, string> closeHash = new Dictionary<int, string>();
        closeHash.Add(47, "Hello");
        closeHash.Remove(closeHash.ElementAt(0).Key);
Run Code Online (Sandbox Code Playgroud)


tho*_*kia 6

在 Generic 集合中使用 Dictionary,您永远不必使用 RemoveAt()。字典中的键值必须是唯一的。

//       Unique Not Unique
//          |     |   
Dictionary<int, string> alphabet = new Dictionary<int, string>();
alphabet.Add(1, "A");
//Adding this will cause an Argument Exception to be thrown
//The message will be: An item with the same key has already been added.
alphabet.Add(1, "A");
Run Code Online (Sandbox Code Playgroud)

如果我想从字母表示例中删除键为 24 的项目,这就是我需要的:

alphabet.Remove(24)
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为永远不会有 2 个键具有相同的值。

现在,如果你想在不知道它的关键的情况下删除一个项目,那就是另一回事了。您需要遍历每个元素并尝试找到与其关联的键。我会使用 linq,有点像这样:

var key = (from item in alphabet
             where item.Value == "K"
             select item.Key).FirstOrDefault();
//Checking to make sure key is not null here
...
//Now remove the key
alphabet.Remove(key)
Run Code Online (Sandbox Code Playgroud)

这两种方式,我都看不到,需要从任何键值必须唯一的列表中使用 RemoveAt(index) 的理由。