473,978 Members | 2,058 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<udLineudLi st = new List<udLine>(10 0);

IEnumerator<udL ineenumerator = udList.GetEnume rator();
while (enumerator.Mov eNext())
{
enumerator.Curr ent.header =
enumerator.Curr ent.header.PadL eft(LongestHead erLength);
}
I really was curious to try this:
public void AlterItem(udLin e ud)
{
ud.header = ud.header.PadLe ft(LongestHeade rLength);
}

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.PadLe ft(LongestHeade rLength);
}

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 4059
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] = theNewValuePerh apsFromTheOldVa lue();
}

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...@g mail.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] = theNewValuePerh apsFromTheOldVa lue();

}

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...@d iscussions.micr osoft.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<udLineudLi st = new List<udLine>(10 0);

IEnumerator<udL ineenumerator = udList.GetEnume rator();
while (enumerator.Mov eNext())
{
enumerator.Curr ent.header =
enumerator.Curr ent.header.PadL eft(LongestHead erLength);
}

I really was curious to try this:
public void AlterItem(udLin e ud)
{
ud.header = ud.header.PadLe ft(LongestHeade rLength);
}

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.PadLe ft(LongestHeade rLength);
}

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
1709
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 colleague did, got an unexpected result, and asked me why. I think I can infer what is occurring, and I was able to find a simple work-around. But I thought I'd ask about it anyway. I've been pushing Python at work for use as a scripting...
5
8812
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 during iteration how can i suppress this message in an actual script and still get the final value of the dict?
6
6077
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 try to modify the objects in the array while iterating through it. I marked the bugs in this code: // Loop through all previously added accounts foreach(Account a in a1) // a1 is an ArrayList { // If name and context is the same if(a.Name ==...
6
7501
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 item in alist x = item
2
1823
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 app, I decided to try one. I changed a "GetCollectionOfObjects"-type method to return a List<custom object>, instantiated objects,and added them to the List. Worked great. My final step was to iterate through them, and there's the rub. Foreach...
4
3008
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. i=0 while(i<len(packet)-4): if packet==Packet("01110"): packet.insert(i, "01111") i+=10 #skip the 5 bits inserted, and skip the 5 bits just checked bc overlap should not trigger insertion
7
4457
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 seem to find a situation where I can use one but not the other. Thanks in advance, --Shafik
4
2832
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 great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the script a JSON list of any size, and the script will create multiple DOM elements with as many attributes...
15
2276
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 to declare var stop if it was not passed to the function. The problem is that stop would be equal to a value dependent on var index that has not been declared yet, but index cannot be created until stop is declared. So you see my chicken and egg...
0
11417
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11590
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10087
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8465
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7620
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6423
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6562
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
5162
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.