C# List<T>.ConvertAll in .NET 2.0

You need to assign the results of the ConvertAll method to the variable like this:

fieldList = fieldList.ConvertAll<string>(new Converter<string, string>(
    delegate(string str)
    {
        str = str.Trim();
        str = str.Replace(' ', '_');
        return str;
    }
));

The ConvertAll method returns a new List<T> so you need to assign the result of the method. If you want to re-use the fieldList variable you can but it may be better to create a new variable to improve the clarity of your code:

List<String> convertedFieldList 
    = fieldList.ConvertAll<string>(new Converter<string, string>(
        delegate(string str)
        {
            str = str.Trim();
            str = str.Replace(' ', '_');
            return str;
        }
));

As Marc Gravell points out in a comment below, you can simplify the syntax of this expression by doing this:

List<String> convertedFieldList 
    = fieldList.ConvertAll<String>(delegate(String str) {
            return str.Trim().Replace(' ', '_');
        });

ConvertAll doesn't change the input list. It returns a new list containing the converted stuff. By the way, you can remove the new Converter<string,string> with C# 2.0+:

List<string> converted = fieldList.ConvertAll<string>
    (delegate(string s) { return s.Trim().Replace(' ', '_'); });

Besides, nothing prevents you from using a C# 3.0 compiler and LINQBridge and target .NET 2.0.

Tags:

C#

List

Delegates