C# 如何在Linq中使用哈希表

C# 如何在Linq中使用哈希表,c#,linq,hashtable,icollection,C#,Linq,Hashtable,Icollection,我试图在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的键 但是上面的查询不起作用,并且给出了编译时错误 错误是: 找不到源类型“System.Collections.ICollection”的查询模式的实现 我做错了什么?我不熟悉C。如何在L

我试图在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的键

但是上面的查询不起作用,并且给出了编译时错误

错误是:

找不到源类型“System.Collections.ICollection”的查询模式的实现


我做错了什么?我不熟悉C。如何在LINQ中使用哈希表?

您不应该首先使用非泛型哈希表。改用通用字典:


您不应该首先使用非泛型哈希表。改用通用字典:

使用字典而不是哈希表请参阅,了解为什么要执行以下操作:

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);
var posi = from a in c.Cast<int>()
           where h[a] == "ABC"
           select a;
但是如果你想要Hastable,那么请看看这个链接

但我的意见是,请使用字典

因为字典是一个通用的集合,它的速度要快得多,因为没有装箱/拆箱

使用字典而不是哈希表请参阅,了解为什么要执行以下操作:

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);
var posi = from a in c.Cast<int>()
           where h[a] == "ABC"
           select a;
但是如果你想要Hastable,那么请看看这个链接

但我的意见是,请使用字典

因为字典是一个通用的集合,它的速度要快得多,因为没有装箱/拆箱


您只需执行以下操作即可获得位置:

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);

但使用字典确实会容易得多。

你只需要这样做就可以得到位置:

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);
但使用字典确实会容易得多。

如果您真的想使用该哈希表而不是字典,您可以执行以下操作:

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);
var posi = from a in c.Cast<int>()
           where h[a] == "ABC"
           select a;
如果确实要使用该哈希表而不是字典,可以执行以下操作:

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);
var posi = from a in c.Cast<int>()
           where h[a] == "ABC"
           select a;

谢谢你的回答,先生,但是我们如何使用哈希表实现同样的功能呢?提前感谢,如果我使用group by a。我得到的值错误无法转换为lambda表达式。为什么?如果不显示group by查询的外观,a怎么可能知道?posi=从a到d group by a.值选择a.键;您应该从LINQ教程开始。您不仅要指定键,还要指定要分组的值。应该将a组的a.值放入gThanks中以获得答案,先生,但是我们如何使用哈希表实现相同的结果呢?提前感谢,如果我使用group by a。我得到的值错误无法转换为lambda表达式。为什么?如果不显示group by查询的外观,a怎么可能知道?posi=从a到d group by a.值选择a.键;您应该从LINQ教程开始。您不仅要指定键,还要指定要分组的值。应按a分组。gI中的值建议使用字典。我建议你用字典。