4

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

为什么这样的东西不起作用?

closeHash.ElementAt<State>(i);

它告诉我以下错误:

错误 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()

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

提前致谢!

格雷格

4

5 回答 5

7

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

        Dictionary<int, string> closeHash = new Dictionary<int, string>();
        closeHash.Add(47, "Hello");
        closeHash.Remove(closeHash.ElementAt(0).Key);
于 2009-12-04T13:19:07.723 回答
6

使用通用集合中的字典,您永远不必使用 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");

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

alphabet.Remove(24)

这是有效的,因为永远不会有 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)

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

于 2009-12-04T13:40:21.213 回答
1

我相信你可以以某种方式做到这一点,但哈希表类型集合通常不适用于“顺序”的概念。在 Java 中,您可以获得一个 Enumerator 或 Iterator 并删除您遇到的第 n 个项目,但同样,我认为这没有意义。

于 2009-12-04T13:02:54.083 回答
0

您只需要使用 System.Linq 就可以使用 ElementAt<> 扩展方法。将其包含在类声明的开头:

using System.Linq;

这应该可以解决问题。

于 2009-12-04T13:10:11.903 回答
0

错误消息暗示您的变量 closeHash 是字典,显然是 Dictionary<"type of i", State>。如果不是,请指定字典的确切声明和“i”。

然后 closeHash[i]应该给出一个 State 类型的值,所以你不需要强制转换。

正如其他人所说,字典没有“顺序”的概念,因此没有“第 n 项”的概念。

于 2009-12-04T13:26:01.967 回答