Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Linq to filter Hashtable based on a property of Values custom object

Tags:

c#

linq

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...

like image 709
Noah Heldman Avatar asked Jun 20 '10 18:06

Noah Heldman


2 Answers

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.

like image 84
Noah Heldman Avatar answered Oct 24 '22 15:10

Noah Heldman


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);
like image 34
LukeH Avatar answered Oct 24 '22 16:10

LukeH