user2623213
user2623213

Reputation: 233

how to use hashtable in Linq

I am trying to use hash table in linq to fetch the key whose value is ABC. What I have done so far:

Hashtable h=new Hashtable ();
h.Add(1 , "ABC");
h.Add(2 , "AgC");
h.Add(3 , "ABC");
h.Add(4 , "AhC");

Expected output: 1, 3 (keys having value "ABC")

ICollection c= h.Keys;

var posi= from a in c
          where h[a]="ABC"
          select a;

But the above query is not working and giving compile time error.

The error is:

could not find an implementation of the query pattern for source type 'System.Collections.ICollection'.

What I am doing wrong? I am new to C#. How to use Hashtable in LINQ?

Upvotes: 2

Views: 21329

Answers (5)

user2991288
user2991288

Reputation: 376

The question is specifically for Hashtables, why do people replays "use dictionary instead" ? I would mark these replies all as out of topic.

Upvotes: 0

Stormenet
Stormenet

Reputation: 26468

If you really want to use that HashTable instead of the Dictionary you can do the following:

var posi = from a in c.Cast<int>()
           where h[a] == "ABC"
           select a;

Upvotes: 2

user3559224
user3559224

Reputation:

Use a Dictionary<int, string> instead of a Hashtable (see here for why) then do the following:

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

But If you want Hastable, Then please take a look this link

link 1

link 2

But My opinion is, Please use Dictionary .

Because Dictionary is a generic collections, And It's are a lot faster as there's no boxing/unboxing.

Upvotes: 2

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

You just need to do this to get position:

int indexOf ( object s, Hashtable h )
{
    foreach ( DictionaryEntry e in h )
        if ( e.Value.Equals(s) )
            return (int)e.Key;
    return -1;
}

and call it like this:

var posi = indexOf("ABC", yourHashTable);

but it is true that using Dictionary would be much easier.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

You should not use non-generic HashTable to start with. Use generic Dictionary<int, string> instead:

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;

Upvotes: 4

Related Questions