Friday, October 3, 2008

C# .NET Extension Methods with a Generic List

well I was asked by a client today on how to write an extention methods and wither 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 sperated list of strings, integers or objects

this example uses generic extention method to convert a list of any type to a string comma sperated list

///
/// Contains List Extention Methods
///

public static class ListExtentions
{
///
/// Converts the current list items to a comma seperated string
///

///
/// My list.
///
public static string ToCommaSeperated(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 the function you can do the following

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

as long as you did a proper override of the ToString() virtual method you should get a proper list of comma seperated User names for example

public class CustomUserObject
{
.
.
.

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




Enjoy ;)

}

0 comments: