debashish giri
debashish giri

Reputation: 69

hashtable keys from multiple objects in linq

Hashtable mainhash = new Hashtable();

        testdata td = new testdata() { value = "td" };
        td.hash.Add("1", "tdvalue1");
        td.hash.Add("2", "tdvalue2");
        td.hash.Add("3", "tdvalue3");
        td.hash.Add("4", "tdvalue4");
        td.hash.Add("5", "tdvalue5");

        testdata td1 = new testdata() { value = "td1" };
        td1.hash.Add("1", "td1value1");
        td1.hash.Add("2", "td1value2");
        td1.hash.Add("3", "td1value3");
        td1.hash.Add("4", "td1value4");
        td1.hash.Add("5", "td1value5");

        testdata td2 = new testdata() { value = "td2" };
        td2.hash.Add("1", "td2value1");
        td2.hash.Add("2", "td2value2");
        td2.hash.Add("3", "td2value3");
        td2.hash.Add("4", "td2value4");
        td2.hash.Add("5", "td2value5");

        testdata td3 = new testdata() { value = "td3" };
        td3.hash.Add("1", "td3value1");
        td3.hash.Add("2", "td3value2");
        td3.hash.Add("3", "td3value3");
        td3.hash.Add("4", "td3value4");
        td3.hash.Add("5", "td3value5");

        testdata td4 = new testdata() { value = "td4" };
        td4.hash.Add("1", "td4value1");
        td4.hash.Add("2", "td4value2");
        td4.hash.Add("3", "td4value3");
        td4.hash.Add("4", "td4value4");
        td4.hash.Add("5", "td4value5");

        mainhash.Add(1, td);
        mainhash.Add(2, td1);
        mainhash.Add(3, td2);
        mainhash.Add(4, td3);
        mainhash.Add(5, td4);

how to select all the keys using SelectMany by Linq into one list?? what i need to do in this??

var values = mainhash.Values.Cast<testdata>().Select(x => x.hash)
                                             .SelectMany(x=> x.Keys);

what is wrong in this??

Upvotes: 1

Views: 1534

Answers (2)

Rahul20
Rahul20

Reputation: 26

try below query -

var values = mainhash.Values.Cast<testdata>().SelectMany(x => x.hash.Keys.Cast<string>());

But, use dictionary instead of hashtable. It actually reduce the overhead of casting the objects.

hope above code helps you !!

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062492

It doesn't know the type to use from Hashtable.Keys.

Try:

var values = mainhash.Values.Cast<testdata>().Select(x => x.hash)
                           .SelectMany(x => x.Keys.Cast<string>());

But better: use Dictionary<TKey,TValue> instead of Hashtable.

Upvotes: 2

Related Questions