user222427
user222427

Reputation:

C# modifing a string array in a foreach loop and changing the same array

Maybe I asked this is a bad way so let me try to explain.

I have a public static string[]

public static string[] MyInfo {get;set;}

I set this via

MyInfo = File.ReadAllLines(@"C:\myfile.txt");

What I want to do is a foreach on each of those lines and modify it based on x number of rules. One the line has been modified change that exisiting line in MyInFo

so

foreach(string myI in MyInfo)
{
string modifiedLine = formatLineHere(myI);
//return this to MyInfo somehow.

}

Upvotes: 0

Views: 92

Answers (4)

Russell Troywest
Russell Troywest

Reputation: 8776

Or with Linq you could do:

MyInfo = MyInfo.Select(x => formatLineHere(x)).ToArray();

Upvotes: 0

danludwig
danludwig

Reputation: 47375

var myInfoList = new List<string>();
foreach (var myI in MyInfo)
{
    var modifiedLine = formatLineHere(myI);
    myInfoList.Add(modifiedLine);

}
MyInfo = myInfoList.ToArray();

Update

You will need a reference to System.Linq in order to use the ToList() and ToArray() extension methods.

Upvotes: 1

Tudor
Tudor

Reputation: 62439

Use a for:

for(int i = 0; i < MyInfo.Length; i++)
{
   MyInfo[i] = formatLineHere(MyInfo[i]);       
}

Upvotes: 1

Fyodor Soikin
Fyodor Soikin

Reputation: 80714

You can't do this in a foreach loop. Use for instead.

Upvotes: 2

Related Questions