473,729 Members | 2,155 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

best way to enumerate List<> & remove unwanted elements?

Obviously you can't just use a simple for loop, since you may skip
over elements.

You could modify the loop counter each time an element is deleted.
But, the loop ending condition must be checked on each iteration,
since the Count changes as you delete elements. I would think it is
guaranteed to be computed each time, and not cached.

So, is this the best way?

List<intmylist = .......somethin g......;
for (int i=0; i<mylist.Count ; i++) {
if (want_to_remove ) {
mylist.RemoveAt (i);
i--;
}
}

Zytan

May 13 '07 #1
56 5198
No, it isn't. To make it easier, you really should enumerate from the
end of the list. This way, you don't have to play around with the index
variable (in this case, i).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Zytan" <zy**********@g mail.comwrote in message
news:11******** **************@ u30g2000hsc.goo glegroups.com.. .
Obviously you can't just use a simple for loop, since you may skip
over elements.

You could modify the loop counter each time an element is deleted.
But, the loop ending condition must be checked on each iteration,
since the Count changes as you delete elements. I would think it is
guaranteed to be computed each time, and not cached.

So, is this the best way?

List<intmylist = .......somethin g......;
for (int i=0; i<mylist.Count ; i++) {
if (want_to_remove ) {
mylist.RemoveAt (i);
i--;
}
}

Zytan

May 13 '07 #2
No, it isn't. To make it easier, you really should enumerate from the
end of the list. This way, you don't have to play around with the index
variable (in this case, i).
Ok. Enumerate with a for loop? And the automatic i-- each time is
sufficient for not skipping elements, I see. Thanks.

(I believe my solution still works, though, right? It's just not the
best way.)

Zytan

May 13 '07 #3

"Zytan" <zy**********@g mail.comwrote in message
news:11******** **************@ u30g2000hsc.goo glegroups.com.. .
Obviously you can't just use a simple for loop, since you may skip
over elements.

You could modify the loop counter each time an element is deleted.
But, the loop ending condition must be checked on each iteration,
since the Count changes as you delete elements. I would think it is
guaranteed to be computed each time, and not cached.

So, is this the best way?

List<intmylist = .......somethin g......;
for (int i=0; i<mylist.Count ; i++) {
if (want_to_remove ) {
mylist.RemoveAt (i);
i--;
}
}
No, you don't decrement (i) like that, you're going to eventually blow up at
that RemoveAt(i).

You just want to do mylist.Clear if you just want to *clear* all elements
out of the list, if that's what you're trying to do.

May 14 '07 #4
Another option is to use RemoveAll(...) with a predicate, perhaps
inline.

Marc

May 14 '07 #5
On Sun, 13 May 2007 16:06:36 -0700, Zytan <zy**********@g mail.comwrote:
Obviously you can't just use a simple for loop, since you may skip
over elements.

You could modify the loop counter each time an element is deleted.
But, the loop ending condition must be checked on each iteration,
since the Count changes as you delete elements. I would think it is
guaranteed to be computed each time, and not cached.

So, is this the best way?
I like Marc's suggestion, to use a predicate delegate to control removal..
It seems tailor-made to the exact scenario you're asking about.

Note that if efficiency is of concern, you may prefer to actually generate
a whole new List<instance instead, copying over only the values you want
to the new List<>. The reason being that, if I recall correctly, the
List<implementa tion uses an array, and insertions and removals in the
array require shifting the contents of the array. In other words, even if
you start at the end, removing elements one at a time involves copying on
average half of the array for each removal.

If you're removing a large percentage of the elements, and you start at
the end of the list, this will help by ensuring that you're shifting the
minimal number of elements with each removal. But you still have the
shift. If you're willing to create a new copy of the List<>, then you can
preallocate the List<to be as large as is necessary to ensure no
reallocations during the processing, and then if you're concerned about
wasted memory once you're done, trim the List<>.

The docs *claim* that RemoveAll() is O(n). So it's possible that
internally, it does exactly what I describe above. It's hard to see how,
if the List<implementa tion really is an array, it could be O(n)
otherwise. But there's a bunch of assumptions in the first part of this
paragraph, so if you really care it seems to me you should probably do
some direct tests between the various methods (and in particular, doing
your own copy-based algorithm vs using RemoveAll()).

If it's not that important (and frankly, it probably isn't until you have
proven to yourself that this part of the code is important for performance
in your application overall), then you should probably just use
RemoveAll() and trust the docs. :)

Finally, note that at the very least I don't see any point in incrementing
a counter that you've just decremented. While the algorithm you posted
could be greatly improved as already mentioned, at a minimum it seems to
me it should look more like this:

List<intmylist = /* whatever */;
int i = 0;

while (i < mylist.Count)
{
if (want_to_remove )
{
mylist.RemoveAt (i);
}
else
{
i++;
}
}

Pete
May 14 '07 #6
No, you don't decrement (i) like that, you're going to eventually blow up at
that RemoveAt(i).
Why? I think it works. Remember the loop increments i itself, so
afte a remove, and decrement, and increment, i is the same value. The
loop code should jump out when there are no elements left.
You just want to do mylist.Clear if you just want to *clear* all elements
out of the list, if that's what you're trying to do.
No, that's not what I am trying to do. I thought my code was clear.
I want to enumerate all elements and remove some based on some
criteria. Perhaps all will be removed, perhaps none, likely only
some.

Zytan

May 14 '07 #7
Another option is to use RemoveAll(...) with a predicate, perhaps
inline.
Interesting, I didn't even know that existed. Thanks, Marc. I think
this is the best method, although it moves the criterion code into
another function (which may be desired if it was complex).

Zytan
May 14 '07 #8
I like Marc's suggestion, to use a predicate delegate to control removal.
It seems tailor-made to the exact scenario you're asking about.
Yes, it does.
Note that if efficiency is of concern
[snip great explanation]
I totally agree. But, efficiency is not a concern, and the list is
small (10's of elements). And yes, even if it was bigger, I shouldn't
care about it until I know it's a bottleneck.

I am also interesting in List<>'s internals. I don't think the docs
lie. Perhaps a look into the C++ STL implementation would reveal some
information about how it can act like an array, and be fast for
modification at the same time. I don't have the time ATM to look this
up.
Finally, note that at the very least I don't see any point in incrementing
a counter that you've just decremented.
Agreed. I like your code better. Don't know why I didn't think about
that.
While the algorithm you posted
could be greatly improved as already mentioned, at a minimum it seems to
me it should look more like this:
Pete, does my algorithm, however bad it is, work? I am 99% sure it
does, but people doubt it.

Zytan

May 14 '07 #9
On Mon, 14 May 2007 10:37:29 -0700, Zytan <zy**********@g mail.comwrote:
[...]
Pete, does my algorithm, however bad it is, work? I am 99% sure it
does, but people doubt it.
I only saw one post doubting it, and I suspect he simply misread the
code. I've been known to do the same from time to time. :)
May 14 '07 #10

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

Similar topics

14
5627
by: Dave | last post by:
Hello all, After perusing the Standard, I believe it is true to say that once you insert an element into a std::list<>, its location in memory never changes. This makes a std::list<> ideal for storing vertices of an arbitrary n-ary tree where a vertex contain pointers to its parent / children. These parent / child vertices need to stay put if we've got pointers to them somewhere! Am I correct in my assertion?
9
7902
by: Paul | last post by:
Hi, I feel I'm going around circles on this one and would appreciate some other points of view. From a design / encapsulation point of view, what's the best practise for returning a private List<as a property. Consider the example below, the class "ListTest" contains a private "List<>" called "strings" - it also provides a public method to add to that list,
7
57554
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list without itterating through the entire collection and building up a list? 2. is there a common base class, collection or interface that can contain either/both of these collection types and then how do you convert or cast from the base to either a...
35
5890
by: Lee Crabtree | last post by:
This seems inconsistent and more than a little bizarre. Array.Clear sets all elements of the array to their default values (0, null, whatever), whereas List<>.Clear removes all items from the list. That part makes a reasonable amount of sense, as you can't actually take items away from an Array. However, there doesn't seem to be a way to perform the same operation in one fell swoop on a List<>. For example:
0
8767
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9293
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
9221
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
9162
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8165
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
6722
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
6028
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
4536
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...
1
3246
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

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.