473,583 Members | 3,114 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 5127
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
5604
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...
9
7872
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...
7
57532
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...
35
5863
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...
0
7827
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...
0
8184
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8328
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...
1
7936
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...
0
5375
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...
0
3820
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...
1
2334
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
1
1434
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1158
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.