473,385 Members | 1,798 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Iterating over a list and altering it?

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<udLineudList = new List<udLine>(100);

IEnumerator<udLineenumerator = udList.GetEnumerator();
while (enumerator.MoveNext())
{
enumerator.Current.header =
enumerator.Current.header.PadLeft(LongestHeaderLen gth);
}
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!


Apr 5 '07 #1
7 4029
OK - you started talking strings, and ended with structs... I think
you need to clarify:

are you a: trying to change the actual contents of the list (i.e. swap
items with replacements), or b: update properties of items that are in
the list?

if "b" then a foreach loop is fine, but the problem here may be that
you are using structures not classes; because these are value-typed
they are going to get copied left right and centre. First rule: .Net
structs should be immutable unless you really, really know what you
are doing. That means that you have to switch to scenario "a".

Now; for "a", note that changing the contents of the list (meaning:
adding, removing, swapping, etc) breaks iterators. This is
intentional. For this scenario the common solution is to use indexer
syntax instead:

for( int i = 0 ; i < list.count ; i++ ) {
list[i] = theNewValuePerhapsFromTheOldValue();
}

Hope this helps,

Marc

Apr 5 '07 #2
In addition to what Marc said, strings are _immutable_ reference type
in .NET so they behave like structs in terms of altering list elements
-- you have to reassign the element in question, ergo you can't use
iterators which are read-only with respect to the list.
--
http://www.kynosarges.de
Apr 5 '07 #3
Sorry, Marc - I started with a simplified question for clarity and then
forgot my simplification. I have a list of structs. Most of the structs are
strings, and I'm trying to alter one of the strings in each struct.

It sounds like I ended up with the right answer in the end, with the for
loop. I take it that the ForEach concept is more to get the data out and put
it somewhere else than to operate on the data itself?

Apr 5 '07 #4
On Apr 5, 10:30 am, "Marc Gravell" <marc.grav...@gmail.comwrote:
OK - you started talking strings, and ended with structs... I think
you need to clarify:

are you a: trying to change the actual contents of the list (i.e. swap
items with replacements), or b: update properties of items that are in
the list?

if "b" then a foreach loop is fine, but the problem here may be that
you are using structures not classes; because these are value-typed
they are going to get copied left right and centre. First rule: .Net
structs should be immutable unless you really, really know what you
are doing. That means that you have to switch to scenario "a".

Now; for "a", note that changing the contents of the list (meaning:
adding, removing, swapping, etc) breaks iterators. This is
intentional. For this scenario the common solution is to use indexer
syntax instead:

for( int i = 0 ; i < list.count ; i++ ) {
list[i] = theNewValuePerhapsFromTheOldValue();

}

Hope this helps,

Marc
I have to disagree that structs should be immutable in .NET - most of
the internal structs provided by .NET are not immutable... in fact,
you'll find more classes are immutable than structs. In general, the
approach is that, if you want a class that you can pass around to lots
of objects, it should be immutable - that avoids the terrifying
headache of aliasing (eg: fonts, strings, etc.). So really, you have
it the other way around - if you want a class that will be used like a
struct, make it immutable. Structs avoid aliasing automatically,
since they're always copy. Personally, I think the important thing is
to always KNOW that a struct is a struct - if you have to include the
word "struct" in it's name, that's fine (since intellisense leaves out
this freakishly crucial piece of information).

Immutable structs defeat most of the advantages of using structs, and
the compiler is sufficiently smart to catch most of the stupid crap
you can get in trouble doing with a struct (IE changing values on a
temporary that will be dropped). Besides, in most DotNet languages,
immutables are a headache to implement (sixteen billion hand-coded
constructors).

Apr 5 '07 #5
On Apr 5, 7:14 am, Evan Reynolds
<EvanReyno...@discussions.microsoft.comwrote:
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<udLineudList = new List<udLine>(100);

IEnumerator<udLineenumerator = udList.GetEnumerator();
while (enumerator.MoveNext())
{
enumerator.Current.header =
enumerator.Current.header.PadLeft(LongestHeaderLen gth);
}

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?
Is there a particular reason why you chose to make udLine a struct
rather than a class? Note that these two keywords have much more
significant implications in C# than in C++.

I suggest that you make udLine a class. Then there will be no need to
pass it using "ref", and your problem should disppear.

Apr 5 '07 #6
Evan Reynolds wrote:
Sorry, Marc - I started with a simplified question for clarity and then
forgot my simplification. I have a list of structs. Most of the structs are
strings, and I'm trying to alter one of the strings in each struct.

It sounds like I ended up with the right answer in the end, with the for
loop. I take it that the ForEach concept is more to get the data out and put
it somewhere else than to operate on the data itself?
Just make it a class instead of a struct, and you can change the members
of the class without problem.

--
Göran Andersson
_____
http://www.guffa.com
Apr 6 '07 #7
Martin Z wrote:
I have to disagree that structs should be immutable in .NET - most of
the internal structs provided by .NET are not immutable... in fact,
you'll find more classes are immutable than structs.
I haven't made a count so I can't say that you are wrong, but I find
that many of the most common structures are immutable, like for example
Color, DateTime, Decimal and TimeSpan. All built-in basic types, like
Int32 and Double, are of course also immutable.

I know of only a few that actually are mutable, like Point, Size and
Rect, and it has been widely debated if making them mutable was a good
move or not.
In general, the
approach is that, if you want a class that you can pass around to lots
of objects, it should be immutable - that avoids the terrifying
headache of aliasing (eg: fonts, strings, etc.). So really, you have
it the other way around - if you want a class that will be used like a
struct, make it immutable. Structs avoid aliasing automatically,
since they're always copy. Personally, I think the important thing is
to always KNOW that a struct is a struct - if you have to include the
word "struct" in it's name, that's fine (since intellisense leaves out
this freakishly crucial piece of information).

Immutable structs defeat most of the advantages of using structs,
Then I am not convinced that you are using structures the way that they
are intended.

If you are using structures as if they were classes, then it would of
course make no sense to make them immutable. On the other hand, in that
case it doesn't really make sense to make them structures either.
and
the compiler is sufficiently smart to catch most of the stupid crap
you can get in trouble doing with a struct (IE changing values on a
temporary that will be dropped). Besides, in most DotNet languages,
immutables are a headache to implement (sixteen billion hand-coded
constructors).
I rarely find that a structure would need more than a few constructors.
With the limited size that is recommneded for structures, there can't be
so many different ways of creating them.

--
Göran Andersson
_____
http://www.guffa.com
Apr 6 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Dave Hansen | last post by:
OK, first, I don't often have the time to read this group, so apologies if this is a FAQ, though I couldn't find anything at python.org. Second, this isn't my code. I wouldn't do this. But a...
5
by: s99999999s2003 | last post by:
hi I wish to pop/del some items out of dictionary while iterating over it. a = { 'a':1, 'b':2 } for k, v in a.iteritems(): if v==2: del a the output say RuntimeError: dictionary changed size...
6
by: Gustaf Liljegren | last post by:
I ran into this problem today: I got an array with Account objects. I need to iterate through this array to supplement the accounts in the array with more data. But the compiler complains when I...
6
by: Steven D'Aprano | last post by:
If I want to iterate over part of the list, the normal Python idiom is to do something like this: alist = range(50) # first item is special x = alist # iterate over the rest of the list for...
2
by: MarkAurit | last post by:
Ive been using arraylists in 1.1 to return collections of custom business objects, and thoroughly enjoyed their simple programming style. After hearing of the advantages of generics during a 2.0...
4
by: dustin.getz | last post by:
consider the following working loop where Packet is a subclass of list, with Packet.insert(index, iterable) inserting each item in iterable into Packet at consecutive indexes starting at index. ...
7
by: Shafik | last post by:
Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't...
4
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a...
15
RMWChaos
by: RMWChaos | last post by:
In my ongoing effort to produce shorter, more efficient code, I have created a "chicken and egg" / "catch-22" problem. I can think of several ways to fix this, none of them elegant. I want my code...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.