我正在尝试使用 linq 中的哈希表来获取值为
ABC
的键。
到目前为止我所做的:
Hashtable h=new Hashtable ();
h.Add(1 , "ABC");
h.Add(2 , "AgC");
h.Add(3 , "ABC");
h.Add(4 , "AhC");
预期输出:1, 3(值为“ABC”的键)
ICollection c= h.Keys;
var posi= from a in c
where h[a]="ABC"
select a;
但是上面的查询不起作用并给出编译时错误。
错误是:
找不到源类型“System.Collections.ICollection”的查询模式的实现。
我做错了什么?我是 C# 新手。如何在 LINQ 中使用哈希表?
您不应该使用非通用的
HashTable
来开始。使用通用 Dictionary<int, string>
代替:
var d = new Dictionary<int, string>();
d.Add(1 , "ABC");
d.Add(2 , "AgC");
d.Add(3 , "ABC");
d.Add(4 , "AhC");
var posi = from a in d
where a.Value == "ABC"
select a.Key;
使用
Dictionary<int, string>
代替哈希表(请参阅 here 了解原因),然后执行以下操作:
var dist = new Dictionary<int, string>();
dist.Add(1 , "ABC");
dist.Add(2 , "AgC");
dist.Add(3 , "ABC");
dist.Add(4 , "AhC");
var keys = dist.Where(d=> d.Value == "ABC").Select(d=> d.Key);
但是如果你想要 Hastable,那么请看看这个链接
但我的意见是,请使用
Dictionary
。
因为
是一个通用集合,而且它的速度要快得多,因为没有装箱/拆箱。Dictionary
如果您真的想要使用
HashTable
而不是Dictionary
,您可以执行以下操作:
var posi = from a in c.Cast<int>()
where h[a] == "ABC"
select a;
您只需执行以下操作即可获得位置:
int indexOf ( object s, Hashtable h )
{
foreach ( DictionaryEntry e in h )
if ( e.Value.Equals(s) )
return (int)e.Key;
return -1;
}
并这样称呼它:
var posi = indexOf("ABC", yourHashTable);
但确实使用
Dictionary
会容易得多。
这个问题是专门针对哈希表的,为什么人们会重播“使用字典代替”?我会将这些回复全部标记为脱离主题。