Convert Dictionary to an Array of KeyValue Collection [C#]

Here, I will try to load a dictionary into an array of a custom class (having a key/value pair) and also into the array of KeyValuePair.
Let’s say you have a class structure as the following:-

public class FieldValueAsTextEntity
{
    private string key;
    public string Key
    {
        get { return key; }
        set { key = value; }
    }

    private string value;
    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }
}

Now to convert a Dictionary to the array of the class, FieldValueAsTextEntity, do the following:-


FieldValueAsTextEntity[] arrayCollection = dictionaryObject.Select(pair=> new FieldValueAsTextEntity()
{
	Key = pair.Key,
	Value = pair.Value
}).ToArray();

OR,

if you sinply want to get the Dictionary object into the array of KeyValuePair, then, do the following:-


KeyValuePair<string, string>[] lstStringCollection;
lstStringCollection = dictionaryObject.Select(pair => new KeyValuePair<string, string>(pair.Key, pair.Value)).ToArray();

NOTE: Here, we have passed the key & Value to the constructor of the KeyValuePair, as its Key & Value property is readonly.More info

Advertisements

Convert DateTime to UNIX timestamp And UNIX timestamp to DateTime

Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970
More Info

So the following two methods convert a DateTime to UNIX timestamp & vice-versa.


internal static string DateTimeToUnixTimeStamp(DateTime date)
{
	return (date - new DateTime(1970, 1, 1, 0, 0, 0).ToLocalTime()).TotalSeconds.ToString();
}

internal static DateTime UnixTimeStampToDateTime(string totalSeconds)
{
	return (new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(Convert.ToDouble(totalSeconds)).ToLocalTime());
}

Convert SQL Time to get only Hour, Min & Sec

I want to convert a Column value whose type is Time to get only the time in the format HH:MM:SS. By default, for, 19:10:00, it was returning, 19:10:00 0000000. Which was obviously not required. So in the SQL query I converted the Time Field to MilitaryTime

SELECT CONVERT(VARCHAR(8), ColumnNameWhoseTypeIsTime, 108) AS MilitaryTime FROM TableName

Happy Coding …