C# ASP.NET SQL SERVER

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

» Similar Posts

  1. Unable to cast object of type 'System.Int32' to type 'System.String'
  2. String Contains From Array with Extension Method
  3. Casting Out Nines

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://guyellisrocks.com/trackback.ashx?id=69

» Comments

    There are no comments. Kick things off by filling out the form below.

» Leave a Comment