2011/01/21

Sort ListBox items (ascending/descending)

1. Create a class that implements IComparer<T> interface.
private class SortListItem : IComparer<ListItem>
{
    public int Compare(ListItem x, ListItem y)
    {
        return String.Compare(x.Value, y.Value);
    }
}

DateTime: Get the first date of the week

1. Create an extension method.
public static class DateTimeExtensions
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }

        return dt.AddDays(-1 * diff).Date;
    }
}

Enum - simple example

class Program
{
  enum DateTypeEnum
  {
    Year = 1,
    Quarter = 2,
    Month = 4,
    Day = 8
  }

  static void Main(string[] args)
  {
    int DateType = 7;
    Console.WriteLine("Your available paying periods are: ");

    //check all available paying methods
    if ((DateType & (int)DateTypeEnum.Year) == (int)DateTypeEnum.Year)
      Console.WriteLine(DateTypeEnum.Year);

    if ((DateType & (int)DateTypeEnum.Quarter) == (int)DateTypeEnum.Quarter)
      Console.WriteLine(DateTypeEnum.Quarter);

    if ((DateType & (int)DateTypeEnum.Month) == (int)DateTypeEnum.Month)
      Console.WriteLine(DateTypeEnum.Month);

    if ((DateType & (int)DateTypeEnum.Day) == (int)DateTypeEnum.Day)
      Console.WriteLine(DateTypeEnum.Day);

    Console.WriteLine();

    int FavoritePayMethod = 4;
    //retrieve enum
    DateTypeEnum BillPeriod = (DateTypeEnum)Enum.Parse(typeof(DateTypeEnum), FavoritePayMethod.ToString());
    Console.WriteLine("Your favorite paying period is \"{0}\".", BillPeriod);
  }
}