C# List<T>.ConvertAll in .NET 2.0
I have a list of strings. All of the strings have whitespace that needs to be converted to underscores. I am fully capable of using a for
or foreach
loop to do this. I am still relatively new to C# and would like to become more familiar with it. With that said, my question is:
How can I get the following code to work in .NET 2.0? When I check fieldList
at the end of the ConvertAll
operation, nothing has changed. Is there an issue with passing the string by value instead of reference?
string fields =
"First Name,Middle Name,Last Name,Birth Date,Gender,Address,City,State,Zip,Email";
List<string> fieldList = new List<string>(fields.Split(','));
fieldList.ConvertAll<string>(new Converter<string, string>(
delegate(string str)
{
str = str.Trim();
str = str.Replace(' ', '_');
return str;
}
));
Please, keep in mind, that I am using .NET 2.0 and cannot currently switch, so I do not have the luxury 开发者_运维百科of using LINQ or Lambdas.
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.
精彩评论