tags:

views:

57

answers:

3

I have a synchronized Hashtable with int as the key, and a custom class called "Job" as the value. I would like to filter this Hashtable based on a property in my Job class called "JobSize". JobSize is just an enum with values Small, Medium, and Large.

It's fine if it needs to be converted to another collection type to do this.

I know there's a slick LINQy way to do this, but I haven't found it yet...

A: 

You should be able to use something like this:

IEnumerable<Job> smallJobs
  = hashTable.Values.Cast<Job>.Where(job => job.JobSize == JobSize.Small);
Martin Liversage
That's what I tried initially, but I got this error:The type arguments for method 'IEnumerable <TSource> System.Linq.Enumerable.Where<TSource>(this IEnumerable<TSource>, Func<TSource,bool>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.So, I did (or, I thought i did):var smallJobs = hashTable.Values.Where<Job>(job => job.JobSize == JobSize.Small);but then, of course, adding <Job> means that I can't convert from the non-generic type to the generic type.
Noah Heldman
`Hastable` is not generic, so you have to `Cast()` it first.
svick
There is no `System.Collections.Generic.Hashtable`.
svick
+3  A: 

It looks like this will work for me:

var smallJobs = hashTable.Values.Cast<Job>().Where(job => job.JobSize == JobSize.Small);

The ".Cast<Job>()" is required because Hashtable is non-generic.

Noah Heldman
You ought to consider using a generic equivalent to `Hashtable` like Dictionary<T, T>. Getting a synchronized Hashtable may not be solving all of your concurrency problems by itself. Also, .NET 4 adds ConcurrentDictionary, which is thread-safe.
Jacob
confirmed, this would do it :)
spookycoder
A: 

Do you need to maintain the keys and values in your filtered Hashtable? If so, try this.

It'll filter the Hashtable and return the filtered results as a strongly typed Dictionary<int,Job>:

var filtered = yourHashtable.Cast<DictionaryEntry>()
                            .Where(x => ((Job)x.Value).JobSize == JobSize.Small)
                            .ToDictionary(x => (int)x.Key, x => (Job)x.Value);
LukeH