C# Tip: Converting Whole Lists in a Single Line of Code

1 במאי 2009

תגיות: , ,
אין תגובות

Lately I wanted to convert a list of items from one type to another. There is the straight way of doing so: writing a loop that iterates through the list, converts each item and generates the output list.

There is a shorter way though.

List has a ConvertAll method. You give it the output type and a delegate that converts a single item and that’s it.

Writing this delegate yourself is just annoying… This is where the Convert class comes into action – you can use the Convert.ToXXX as the conversion delegate:

 

// Original list
List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });

// Convert all items to strings
List<string> listOfStrings = list.ConvertAll<string>(Convert.ToString);

// Convert all items to chars
List<char> listOfChars = list.ConvertAll<char>(Convert.ToChar);

// Convert all items to bytes
List<byte> listOfBytes = list.ConvertAll<byte>(Convert.ToByte);

That’s it.

All the best,

Shay.

Share it: DotNetKicks | DotNetShoutout

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. (*) שדות חובה מסומנים