473,386 Members | 1,610 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,386 software developers and data experts.

Changing a list while iterating over its elements with a foreachloop

I am somewhat new to C# and I ran into a problem in a small program I am
writing for teaching myself.

I am handling a list ob objects and I want to delete some of them inside
a loop like in:

foreach (Object object in objList)
{
if (object.status() == deleted)
{
objList.remove(object);
}
}

The problem here is that the list is changed while iterating over its
elements. I know one could make this work in C++ because the remove
method of the C++ STL list template returned an iterator to the next
valid object of the list. Is there any equivalent or other elegant
solution to do something like this?
I have read through all documentation I could find about the list class
in the past two days but I didn't find anything and I don't have much
literature on C# yet either.

Any help would be appreciated.
Apr 18 '07 #1
9 10679
System.Collections.Generic.List has a RemoveAll function:

List<objectlist = new List<object>();

Predicate<objectpred = delegate(object item) { return item.status ==
deleted; };
list.RemoveAll(pred);

-James

Apr 18 '07 #2
james schrieb:
System.Collections.Generic.List has a RemoveAll function:

List<objectlist = new List<object>();

Predicate<objectpred = delegate(object item) { return item.status ==
deleted; };
list.RemoveAll(pred);
Yes, but that only works if I just want to delete.. what if the foreach
loop contains stuff like this:

{
if (object.status() == deleted) do this

if (object.status() == something else) do this

..
..
..
}

See my problem? I kinda want to be able to do many things in one foreach
loop depending on a condition, including removing objects. I don't want
to have a seperate loop or command just to delete something from the
loop, I want to be able to do whatever is necessary depending on the
state within one single loop. Is that possible in C# with the List class?
I mean using the removeAll command as a seperate command before the
other loop is ok, but not the most elegant way to do it...
Apr 18 '07 #3
Hi,
The problem here is that the list is changed while iterating over its
elements. I know one could make this work in C++ because the remove method
of the C++ STL list template returned an iterator to the next valid object
of the list. Is there any equivalent or other elegant solution to do
something like this?

You will have to keep track of the instances you need to remove and remove
them later on another loop:

ArrayList toDel = new ArrayList()
foreach (Object obj in objList)
{
if (obj.status() == deleted)
{
toDel.Add( obj)
}
}

foreach( Object obj in toDel )
objList.remove(obj);


Apr 18 '07 #4
Hi,

"Andreas Schmitt" <ke**********@gmx.dewrote in message
news:f0*************@news.t-online.com...
james schrieb:
>
See my problem? I kinda want to be able to do many things in one foreach
loop depending on a condition, including removing objects. I don't want to
have a seperate loop or command just to delete something from the loop, I
want to be able to do whatever is necessary depending on the state within
one single loop. Is that possible in C# with the List class?
I mean using the removeAll command as a seperate command before the other
loop is ok, but not the most elegant way to do it...
You can modify the status of the instances. what You can not do is modify
the list
Apr 18 '07 #5
the foreach loop uses an iterator, so if you were to remove an item from the
list, the iterator is no longer valid. to prevent errors or
unwanted/unexpected results, you cant remove items from a list your iterating
in a foreach loop.
--
-iwdu15
Apr 19 '07 #6
You could try doing it backwards so it's not trying to access past the end
of the list. I think I actually used this somewhere, but I can't find it
right now, so maybe I didn't; I can't remember. Here's the theory. It's
free to try!

For (i = myList.Count-1; i < 0; i--)
if (obj[i].Status == deleted)
obj[i].remove();

Robin S.
---------------------

"Andreas Schmitt" <ke**********@gmx.dewrote in message
news:f0*************@news.t-online.com...
>I am somewhat new to C# and I ran into a problem in a small program I am
writing for teaching myself.

I am handling a list ob objects and I want to delete some of them inside
a loop like in:

foreach (Object object in objList)
{
if (object.status() == deleted)
{
objList.remove(object);
}
}

The problem here is that the list is changed while iterating over its
elements. I know one could make this work in C++ because the remove
method of the C++ STL list template returned an iterator to the next
valid object of the list. Is there any equivalent or other elegant
solution to do something like this?
I have read through all documentation I could find about the list class
in the past two days but I didn't find anything and I don't have much
literature on C# yet either.

Any help would be appreciated.

Apr 19 '07 #7
On Apr 19, 1:21 am, "RobinS" <Rob...@NoSpam.yah.nonewrote:
>
For (i = myList.Count-1; i < 0; i--)
if (obj[i].Status == deleted)
obj[i].remove();
I think you mean

For (i = myList.Count-1; i 0, i--) //Note i 0
Apr 19 '07 #8

"Andreas Schmitt" <ke**********@gmx.dewrote in message
news:f0*************@news.t-online.com...
>I am somewhat new to C# and I ran into a problem in a small program I am
writing for teaching myself.

I am handling a list ob objects and I want to delete some of them inside a
loop like in:

foreach (Object object in objList)
{
if (object.status() == deleted)
{
objList.remove(object);
}
}

The problem here is that the list is changed while iterating over its
elements. I know one could make this work in C++ because the remove method
of the C++ STL list template returned an iterator to the next valid object
of the list. Is there any equivalent or other elegant solution to do
something like this?
C++ list is like .NET LinkedList
C++ vector is like .NET List
I have read through all documentation I could find about the list class in
the past two days but I didn't find anything and I don't have much
literature on C# yet either.

Any help would be appreciated.

Apr 19 '07 #9

"Chris Dunaway" <du******@gmail.comwrote in message
news:11**********************@b58g2000hsg.googlegr oups.com...
On Apr 19, 1:21 am, "RobinS" <Rob...@NoSpam.yah.nonewrote:
>>
For (i = myList.Count-1; i < 0; i--)
if (obj[i].Status == deleted)
obj[i].remove();

I think you mean

For (i = myList.Count-1; i 0, i--) //Note i 0

Thank you, you're right. I was thinking "Do Until" not "Do While". It was
really late when I posted that.

Robin
Apr 20 '07 #10

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

Similar topics

1
by: Mirek Endys | last post by:
I have serialized list of my object in a xml file. What is the best way to update only one object and save it back into the xml file. Do I have to load full list, update one item and save the list...
2
by: Juliano.net | last post by:
How can I get a list of elements inside a tag and when I find one element of a type that I choose I can change its ID and CLASS attribute? Ex: <div id="content"> <!-- I want to get the list of...
1
by: irq3 | last post by:
I want to make a horizontal list elements, whose widths are determined by their "width" property. "width" doesn't work on inline elements, so I can't use <spanas I normally would if the width was...
1
by: eight02645999 | last post by:
hi say i have a list alist = I wanted to change the elements , say alist . If i do alist = "t" , it gives which is not what i want. I wanted alist =
1
by: irfath | last post by:
Write an interactive program that reads three (3) lists of numbers, which are stored in three separate files, and creates one (1) sorted list. Each file should contain not more than 15 numbers....
1
by: technod | last post by:
Hi, I have constructed a clickable list of words which are added to a select box. I then have buttons to move the added elements up or down in the list. The code below seems to work fine for...
2
by: psbasha | last post by:
Hi Is it possible to Concatenate/Append list of elements into a single string as shown below ? I/P: list = O/P:
2
by: physicslad | last post by:
Hi, I have in my program a list of lists of variables. These variables change as the program runs. I would like to be able to link meaningful names to the variables. So, say I have a list of...
10
by: Debajit Adhikary | last post by:
I have two lists: a = b = What I'd like to do is append all of the elements of b at the end of a, so that a looks like: a =
8
by: CatchSandeepVaid | last post by:
Say i have one-to-many relationship between Product and ProductNames. So Product has a List of ProductNames. Actually we are using List for productNames.and for list, in order to maintain...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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.