views:

207

answers:

5

Hi everyone:

I am embarrassed to ask, but what is the best way to add key/value pair data in cache (HttpRuntime.Cache) to a DataTable?

I'm currently dumping the key/value pair data from cache into a HashTable, which becomes the DataSource for a Repeater object. Unfortunately, I cannot sort the data in the Hashtable and therefore thought a DataTable (being the DataSource for the Repeater) would solve my dilema.

Thanks, Yoav

A: 

Is there some reason you odn't want to store the Original Data table in your cache? (Besides the obvious high object weight of it, I mean?) Is it something you can share between all users in a read-only fashion? If so, it's probably a good candidate for caching in some format (maybe IDictionary?).

No Refunds No Returns
+1  A: 

Have you had a look at SortedList Class, or SortedDictionary Class

Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<(Of <(T>)>) implementation.

astander
A: 

Or you can create you own class having the properties it will be bind to the repeater later on and add them into list of that type and you can sort them easily by linq

//your data container class 
 public class MyClass
    {
        public string Name { get; set; }
    }

//Put all classes into the list before caching it 
List<MyClass> source = new List<MyClass>() ; 

//use this to sort with any kind of data inside your own defined class 
var sortedResult = source.OrderBy(x => x.Name);
Amgad Fahmi
A: 
This should do the trick:

Sub Main() Handles Me.Load
    Dim Hash As New Hashtable

    Hash.Add("Tom", "Arnold")
    Hash.Add("Sly", "Stallone")

    HashToDataTable(Hash)
End Sub

Function HashToDataTable(ByVal Hash As Hashtable) As Data.DataTable
    Dim Table As New Data.DataTable()

    Table.Columns.Add("Key", GetType(String))
    Table.Columns.Add("Value", GetType(Object)) 'You can use any type you want.

    For Each Key In Hash.Keys
        Table.Rows.Add(Key, Hash(Key))
    Next

    Return Table
End Function
diamandiev
+1  A: 

If you simply want to copy each key/value pair from the cache to a DataTable:

DataTable table = new DataTable();
table.Colums.Add("key", typeof(string));
table.Colums.Add("value", typeof(string));

foreach (DictionaryEntry entry in HttpRuntime.Cache)
{
    table.Rows.Add(entry.Key, entry.Value);
}

This assumes that both keys and values are of type string, but if this is not the case, simply replace the types mentioned in line #2 and #3 in the code.

The newly created DataTable can be bound to a Repeater using code like this:

myRepeater.DataSource = table;
myRepeater.DataBind();
Jørn Schou-Rode