Browsing all articles from January, 2011
Jan
28

Code Snippet 1: Best way to convert string to DateTime

This is the best way to convert string to Date
the following code convert string to date which is in
“d/M/yyyy” or “dd/MM/yyyy” or “d/MM/yyyy” or “dd/M/yyyy”

string MyDate = "12/12/2012";
DateTime _MyDate;
if (!DateTime.TryParseExact(MyDate, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out _MyDate))
{
this._message = "Invalid Date";
// do here with invalid date
}
_MyDate
// do here  with valid date

Function:

public static bool ToDate(string DateString, out DateTime Date)
        {
            if (!DateTime.TryParseExact(DateString, new[] { "d/M/yyyy", "dd/MM/yyyy", "d/MM/yyyy", "dd/M/yyyy" }, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out Date))
                return false;
            return true;
        }
Jan
27

Remove duplicates in a string array

These are the followings ways, where we can filter a string array to remove the duplicates.

HashSet   
public static string[] RemoveDuplicates(string[] s)
{
HashSet set = new HashSet(s);
string[] result = new string[set.Count];
set.CopyTo(result);
return result;
}
List 1   
private static string PreviousItem;

private static bool Match(string item)
{
    bool result = (item == PreviousItem);
    PreviousItem = item;
    return result;
}

public static string[] NoDuplicates(string[] input)
{
    PreviousItem = null;
    List<string> result = new List<string>(input);
    result.Sort();
    result.RemoveAll(Match);
    return result.ToArray();
}
Follow us on Twitter! Follow us on Twitter!
FoxSparrow Tweets

Categories