Sarat
Sarat

Reputation: 273

How to add keys to hashtable from a List in the same order in C#

I have a integer List List<int> iFaciltyReqId = new List<int>(); and its elements are enter image description here

I need to order the hashtable below like the above List(need to exclude if the element not exist)

My hashtable is enter image description here

Result should be hastable keys in the order 1153 1168 1155 1152 1176 676

I tried as below, but the result is not meeting my expectation

foreach (var c in iFaciltyReqId)
            {

                foreach (var d in ohmItemSeqs.Keys)
                {
                    if (Convert.ToInt32(c) == Convert.ToInt32(d))
                    {
                        sortedohmItemSeqs.Add(c, ohmItemSeqs.Values);
                    }
                }
            }

and result was enter image description here Any help will be appreciated.

Upvotes: 2

Views: 184

Answers (2)

dnickless
dnickless

Reputation: 10918

I would suggest you simply take your list and return everything that's also in the hash table like so:

var result = yourList.Where(i => yourHashTable.Contains(i)); // works for both HashSet<int> and Hashtable

Upvotes: 2

sbsd
sbsd

Reputation: 306

A Hashtable is fundamentally an unordered data structure, so you'll want to look at alternatives if maintaining order is important.

If you want the order to be determined by insertion, OrderedDictionary may be a suitable option, although that depends on what your other needs for the object are.

Upvotes: 1

Related Questions