2010년 3월 9일 화요일

C# Tips

▣ Regular Expressions
[code c#]
using System;
using System.Text.RegularExpressions;

public static string CleanupFileName(string inputFileName, string replaceString)
{
    string regexSearch = string.Format("{0}{1}", new string(System.IO.Path.GetInvalidFileNameChars()), new string(System.IO.Path.GetInvalidPathChars()));

    string excapeString = Regex.Escape(inputFileName);

    Regex regEx = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));

    return regEx.Replace(inputFileName, replaceString == null ? string.Empty : replaceString);
}

[/code]

▣ Sorting a Generic List<T>
[code c#]
using System;
using System.Collections.Generic;

public class MyItem
{
    public int ID;
    public string Name;

    public MyItem(int id, string name)
    {
        this.ID = id;
        this.Name = name;
    }
}

public void SortList()
{
    List<MyItem> itemList = new List<MyItem>();
    itemList.Add(new MyItem(0, "CBA"));
    itemList.Add(new MyItem(1, "ABC"));
    itemList.Add(new MyItem(2, "BCA"));

    itemList.Sort(delegate(MyItem p1, MyItem p2)
    {
        return p1.Name.CompareTo(p2.Name);
    });

    foreach (MyItem curItem in itemList)
    {
        System.Diagnostics.Debug.WriteLine(curItem.Name);
    }
}
[/code]