G
Guest
I am a C++ programmer and have been learning C#. I have constructed a List<>
and I want to iterate over it, altering each string in the list.
In C++, I'd just create an iterator and walk the list, so I was looking for
something similar in C#. I looked at foreach, List.ForEach, and IEnumerator.
The problem is that all of them seem to return readonly pointers to the
items in the List. Therefore I can't alter the list. So I'm using a for
loop, but ... I'm just baffled that there aren't any sort of iterators that
let me alter the list. I have the feeling that there are, or that I'm just
not using these right. So I figured I'd ask!
Here's some of the code I tried ... note that udLine is a struct, and udList
is a List of those structs.
public List<udLine> udList = new List<udLine>(100);
IEnumerator<udLine> enumerator = udList.GetEnumerator();
while (enumerator.MoveNext())
{
enumerator.Current.header =
enumerator.Current.header.PadLeft(LongestHeaderLength);
}
I really was curious to try this:
public void AlterItem(udLine ud)
{
ud.header = ud.header.PadLeft(LongestHeaderLength);
}
and then call:
udList.ForEach(AlterItem);
but nothing happened. My guess was that the ud was getting copied, so I
made it a ref argument:
public void AlterItem(ref udLine ud)
{
ud.header = ud.header.PadLeft(LongestHeaderLength);
}
udList.ForEach(ref AlterItem);
but the compiler really didn't like that.
So I'm using a for loop. But is there a way to make either of the above
statments work?
Thank you!
and I want to iterate over it, altering each string in the list.
In C++, I'd just create an iterator and walk the list, so I was looking for
something similar in C#. I looked at foreach, List.ForEach, and IEnumerator.
The problem is that all of them seem to return readonly pointers to the
items in the List. Therefore I can't alter the list. So I'm using a for
loop, but ... I'm just baffled that there aren't any sort of iterators that
let me alter the list. I have the feeling that there are, or that I'm just
not using these right. So I figured I'd ask!
Here's some of the code I tried ... note that udLine is a struct, and udList
is a List of those structs.
public List<udLine> udList = new List<udLine>(100);
IEnumerator<udLine> enumerator = udList.GetEnumerator();
while (enumerator.MoveNext())
{
enumerator.Current.header =
enumerator.Current.header.PadLeft(LongestHeaderLength);
}
I really was curious to try this:
public void AlterItem(udLine ud)
{
ud.header = ud.header.PadLeft(LongestHeaderLength);
}
and then call:
udList.ForEach(AlterItem);
but nothing happened. My guess was that the ud was getting copied, so I
made it a ref argument:
public void AlterItem(ref udLine ud)
{
ud.header = ud.header.PadLeft(LongestHeaderLength);
}
udList.ForEach(ref AlterItem);
but the compiler really didn't like that.
So I'm using a for loop. But is there a way to make either of the above
statments work?
Thank you!