how to use hashtable in Linq

18,016

Solution 1

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;

Solution 2

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.

Solution 3

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;
Share:
18,016

Related videos on Youtube

user2623213
Author by

user2623213

Updated on June 04, 2022

Comments

  • user2623213
    user2623213 almost 2 years

    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?

  • user2623213
    user2623213 about 10 years
    Thanks for the answer sir but how can we implement the same using Hashtable? Thanks in advance
  • user2623213
    user2623213 about 10 years
    And also if I am using group by a.Value I am getting error can't convert to lambda expression. Why?
  • MarcinJuraszek
    MarcinJuraszek about 10 years
    How could a possibly know without you showing how query with group by looks like?
  • user2623213
    user2623213 about 10 years
    posi = from a in d Group by a.Value select a.Key;
  • MarcinJuraszek
    MarcinJuraszek about 10 years
    You should start with LINQ tutorials. You have to specify not only the key, but also what values you want to group. Should be group a by a.Value into g
  • Dennis_E
    Dennis_E about 10 years
    @user2623213 A Dictionary IS a Hashtable. It's just a generic version.