views:

112

answers:

1

I'm working with a set of legacy DAO code that returns an IList, where each Hashtable represents the row of a dynamically executed SQL query. For example, the List might contain the following records/hashtables:

Hashtable1:
Key:Column15, Value:"Jack"
Key:Column16, Value:"Stevens"
Key:Column18, Value:"7/23/1973"
Key:Column25, Value:"Active"

Hashtable2:
Key:Column15, Value:"Melanie"
Key:Column16, Value:"Teal"
Key:Column18, Value:"null"
Key:Column25, Value:"Inactive"

Hashtable3:
Key:Column15, Value:"Henry"
Key:Column16, Value:"Black"
Key:Column18, Value:"3/16/1913"
Key:Column25, Value:"Active"

Use of a static type instead of a Hashtable is out of the question because the result of the query is unknown at run time; both the number of columns and the nature of those columns is completely dynamic.

I'd like to be able to perform Linq based operations on this data set (grouping, ordering etc), but I absolutely can't get my head around what the syntax might look like. As a simple example, let's say I want to sort the list by Column15 descending. The best syntax I've come up with is:

var rawGridData = (List<Hashtable>) _listDao.GetListGridContents(listID, null, null);   
var sortedGridData = rawGridData.OrderBy(s => s.Keys.Cast<string>().Where(k => k == "Column15"));

However, this yields an exception when sortedGridData is enumerated: "At least one object must implement IComparable."

I've been struggling with this problem for days and am near my wit's end...please help!

+1  A: 

This should get you started:

var sortedGridData = rawGridData.OrderBy(r => r["Column15"])

This maps each "record" to the value in "Column15" and then orders the resulting projection. This is easily generalizable.

Jason
Works perfectly. I had a hunch it was going to be something super simple. Just like me to over-complicate a simple problem. Thanks!
Dirk
The OP wanted descending order, so OrderByDescending would be the appropriate method
Winston Smith
Actually, what he was really after was how to perform operations on his result set such as grouping, sorting, etc. The hangup was on how to project each instance of `HashTable` a value representing the specific column that he was after. So the key is projecting each instance of `HashTable` to that value. The rest is just details.
Jason