Wednesday, February 25, 2009

Converting List types in C#

I was searching earlier and saw that many people's solution to this issue is implementing a for loop. No need with >= c#2.0 List has a very handy ConvertAll method.

I have a quick example of the awesome power in 2 lines of code.Convert List<int> into a List<string> or List<int> into an array of strings which I needed to join a list of ids.

List<int> myList = new List<int>(){ 101,202,332,343};
string sIdList = string.Join(",", myList.ConvertAll<string>(delegate(int i){return i.ToString();}).ToArray());

sIdList output is "101,202,332,343"

I hope this helps someone else.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.