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. LINQ secondary sort using extension method syntax
  3. String Contains From Array with Extension Method

» Trackbacks & Pingbacks

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

» Comments

  1. MBJB avatar

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

    MBJB — June 22, 2009 5:14 PM
  2. guy ellis avatar

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

    guy ellis — June 22, 2009 6:31 PM

» Leave a Comment