Tuesday, August 19, 2008

Hashtable keys intersect with list of Int32

The problem: You have a classic Hashtable. Although the keys are strings they hold only ints. You also have a list of ints. You want to find out if any of the keys from the Hashtable are in the list of ints. How do you do this in one line of LINQ?

The solution, using LINQ, that I came up with is:

            // Setup the test data
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            ht.Add("1", new object());
            ht.Add("2", new object());

            List<int> second = new List<int>();
            second.Add(2);
            second.Add(3);

            // Query the data
            bool containsKey = ht.Keys.Cast<string>().Select(a => Convert.ToInt32(a)).ToList().Intersect(second).Count() > 0;

            // Print the result
            Console.Write("Contains Key: {0}", containsKey);
 

2 comments:

  1. Thank you, I was strugling with this for an hour before I found your site.

    ReplyDelete
  2. If I've helped one person then my mission is complete - great that it helped solve your problem.

    ReplyDelete