Click here to Skip to main content
15,881,616 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I have an error stating "Cannot assign to '***' because it is a 'foreach iteration variable'"

So I have the following foreach loops, please tell me their alternative for loops, so that I can proceed with the program.

foreach (string line in Regex.Split(ArticleData, Environment.NewLine))
{
    while (line.EndsWith(('\n').ToString()) || line.EndsWith(('\r').ToString()))
    {
        line = line.Substring(0, line.Length - 1);


foreach (string ncxline in Regex.Split(Convert.ToString(TotalDataForOPF_NCX), Environment.NewLine))
{
    while (ncxline.EndsWith(('\n').ToString()) || ncxline.EndsWith(('\r').ToString()))
        {
            ncxline = ncxline.Substring(0, ncxline.Length - 1);


Please help.

Regards
Aman Chaurasia

What I have tried:

I have not tried anything because I don't know how to proceed
Posted
Updated 29-May-18 3:54am
v2
Comments
Richard MacCutchan 29-May-18 5:13am    
('\n').ToString()
Why on earth are you calling ToString on a string character? If you want it as a string constant rather than a character then use double quotes.
F-ES Sitecore 29-May-18 6:28am    
'\n' isn't a string :)
Richard MacCutchan 29-May-18 6:43am    
No, but it is a character.
Primo Chalice 29-May-18 6:02am    
Will do that, but one question. Why do the foreach variables in Visual Basic work fine but show an error in C#?

Create a string array from your Regex operation and use an integer variable.
 
Share this answer
 
Comments
Primo Chalice 29-May-18 6:02am    
Will do that, but one question. Why do the foreach variables in Visual Basic work fine but show an error in C#?
Never try to modify an iterator variable; never try to modify a collection you are enumerating in the enumerator.

If what you are after is an array of strings made from stripping line endings as you parse the lines of a file:

1. handle any style of line-break:

char[] lineEndings = new char[]{'\r','\n'};

2. use example:

string[] strippedLines = ArticleData.Split(lineEndings, StringSplitOptions.RemoveEmptyEntries);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900