Home > other >  C# - Capitalize in foreach
C# - Capitalize in foreach

Time:06-30

I've got an issue with capitalizing a list of strings in a foreach statement. I'm pretty sure it is very simple, but actually I cannot see why it is not updating the strings in the list. I have the following method:

public static string Capitalize(string fileName)
{
     TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
     List<string> splittedFileName = fileName.Split('_').ToList();
     splittedFileName.ForEach((file) => file = textInfo.ToTitleCase(file));
     return String.Join("_", splittedFileName);
} 

First it splits provided a string by underscore into a List. Then I thought I can use foreach to update each element (make the first letter uppercase). I.e. I call the method this way:

var capitalized = Export.File.Capitalize("test_all_first_letters_uppercase");

If I debug the solution it updates the file variable, but the List entries are not being updated. So the return value of my example is

test_all_first_letters_uppercase

but it should be

Test_All_First_Letters_Uppercase

As I said, I'm sure it is a simple reason for it, but actually I cannot see it.

CodePudding user response:

This line:

splittedFileName.ForEach((file) => file = textInfo.ToTitleCase(file));

just assigns a by-value parameter (file) which has no effect. Note, it is not ref string file.

You can use .ConvertAll instead, or Linq. Examples:

var changed = splittedFileName.ConvertAll(file => textInfo.ToTitleCase(file));
// or:
var changed = splittedFileName.Select(file => textInfo.ToTitleCase(file));

In both cases, you can use the "method group" directly:

var changed = splittedFileName.ConvertAll(textInfo.ToTitleCase);
// or:
var changed = splittedFileName.Select(textInfo.ToTitleCase);

CodePudding user response:

when you are use foreach, you are not actually updating the items in the list. You are just going through them and making an operation on each value in the list.

For your case, I suggest you use a for loop.

for (int index = 0; index < mylist.Count(); index  )
{
     mylist[index] = TextInfo.ToTitleCase(mylist[index])
}

CodePudding user response:

In generalized case, you can try using regular expressions, e.g.

string demo = "it is a demo: a_b_c, ABC, aBc, abC";

// Capitalizes every first letter in the word
// It Is A Demo: A_B_C, ABC, ABc, AbC
string result = Regex.Replace(demo, @"(?:\b|_)\p{Ll}", m => m.Value.ToUpper());

Or if you are looking for a title case:

string demo = "it is a demo: a_b_c, ABC, aBc, abC";

// Capitalizes every first letter in the word
// It IS A Demo: A_B_C, ABC, Abc, Abc
string result = Regex.Replace(
  demo, 
 @"(?:\b|_)\p{L} ", 
  m => CultureInfo.CurrentCulture.TextInfo.ToTitleCase(m.Value));
  •  Tags:  
  • c#
  • Related