views:

114

answers:

2

I need to convert all DateTime values to String, though out my project, all of my code at the end follows 1 function, where I have 4 different Hashtables (actually XmlRpcStruct Object of CookComputing xmlrpc library).

is there any way that without iterating on each hash table - I can convert the values of hashtable having datetime -> string.

without iterating - I mean just to make the processing faster, but I need to solve it for nested hashtables where key contains another hashtable too.

A: 

Why can't you just convert the date to a time when you are adding it into the hashtable?

myHashTable.Add("ADate", DateTime.Now.ToString());
James
because there are more then 150 occourance of DateTime, and developers can make mistake in future by forgetting to convert it to string, as till now we use to pass DateTime - to Server and now Server doesn't accept DateTime in its newer version !!! |)
Tumbleweed
How exactly is it passed to the server? The full hashtable or is the hashtable iterated over and the individual values passed over?
James
Full hashtable is passed !
Tumbleweed
How is your hashtable types defined? Hashtable<string, DateTime>?
James
yes key is date and value is DateTime
Tumbleweed
I am confused as a Hashtable takes in object values only, so you must be doing some form of conversion from object to type somewhere anyway?
James
"date":DateTime.Now like this... yes there are some type casting too
Tumbleweed
+1  A: 

You could process your hashtable, just before sending to that server. Inspect each object. Is it really a DateTime, then replace it with a .ToString with the appropriate format.

public static void ProcessHT(Hashtable ht)
{
 Hashtable dates = new Hashtable();

 foreach(DictionaryEntry de in ht)
 {
  if (de.Value is DateTime)
   dates.Add(de.Key, de.Value);
 }

 foreach(DictionaryEntry de in dates)
 {
  ht.Remove(de.Key);
  ht.Add(de.Key, ((DateTime)de.Value).ToString("s"));
 }
}

public static void RunSnippet()
{
 Hashtable ht = new Hashtable();

 ht.Add("1", "one");
 ht.Add("date", DateTime.Today);
 ht.Add("num", 1);
 Print(ht);
 WL("---");
 ProcessHT(ht);
 Print(ht);
}

private static void Print(Hashtable ht)
{
 foreach (DictionaryEntry de in ht)
 {
  WL("{0} = {1}", de.Key, de.Value);
 }
}
Hans Kesting
what if I have nested hashtable, I found some where I my hashtable itself contains another hashtable. (sweat)
Tumbleweed
This kinda defeated the purpose of your question as you asked is there way to convert all DateTime value without iterating....this is iterating.
James
Yes james, but I'm stuck even with iterating now causing errors for nested hashtables.
Tumbleweed
@shahjapan, provide an example of your code...
James
If there is a nested hashtable, check for that in the ProcessHT method and recursively call it again: if (de.Value is Hashtable) ProcessHT((Hashtable)de.Value);
Hans Kesting