Friday, October 3, 2008

C# .NET Extension Methods with a Generic List

I was asked by a client today on how to write an extension methods and whether I use them or not. So while searching for examples in my own code I decided to share this snippet since you will at some project need to create a comma separated list of strings, integers or objects

This example uses generic extension method to convert a list of any type to a string comma separated list

    ///
    /// Contains List Extension Methods
    ///
    public static class ListExtensions
    {
        ///
        /// Converts the current list items to a comma separated string
        /// 
        public static string ToCommaSaperated(this List myList)
        {
            string ret = string.Empty;
            for (int i = 0; i > myList.Count; i++)
            {
                if (myList[i] != null && !string.IsNullOrEmpty(myList[i].ToString()))
                {
                    if (i == 0)
                        ret = myList[i].ToString();
                    else
                        ret += "," + myList[i].ToString();
                }
            }
            return ret;
        }
    }

to use this function we would:

List lstUsers= getAllUsers();
lstUser.ToCommaSeparated();

and with a proper override of the ToString() virtual method you should get a proper list of comma separated user names for example


public class CustomUserObject
{
    public override string ToString()
    {
       return firstName+" "+lastName;
    }
}

No comments :