correct way of looping through a list and remove items
I wrote a function to go through a list and remove list items if some conditions where met. My program crashed on it, and after a while i concluded that the outer for loop, goes through all items in the list.
While at the same routine the list of item can get shorter.
// Lijst is a list of a struct that contains a value .scanned and .price
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
// (removed deletion of list item i here)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i); //<-moved to here
Now i wonder whats the correct to do this, without getting index out of range errors.
c# list
|
show 7 more comments
I wrote a function to go through a list and remove list items if some conditions where met. My program crashed on it, and after a while i concluded that the outer for loop, goes through all items in the list.
While at the same routine the list of item can get shorter.
// Lijst is a list of a struct that contains a value .scanned and .price
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
// (removed deletion of list item i here)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i); //<-moved to here
Now i wonder whats the correct to do this, without getting index out of range errors.
c# list
3
Run the loop from count to 0
– Mohit Shrivastava
Jan 28 '16 at 9:44
1
While removing items from list, you want the loop to run backwards.
– Haris
Jan 28 '16 at 9:46
1
Possible duplicate of C# List - Removing items while looping / iterating
– Rezoan
Jan 28 '16 at 9:47
1
You could achieve the same thing with a line of LINQ:list.RemoveAll(x => x.Scanned);
– TVOHM
Jan 28 '16 at 9:47
2
@TVOHM - Just to be pickylist.RemoveAll(x => x.Scanned)
isn't LINQ. It predates LINQ. It's simply an anonymous method cast as aPredicate<T>
delegate.
– Enigmativity
Jan 28 '16 at 9:50
|
show 7 more comments
I wrote a function to go through a list and remove list items if some conditions where met. My program crashed on it, and after a while i concluded that the outer for loop, goes through all items in the list.
While at the same routine the list of item can get shorter.
// Lijst is a list of a struct that contains a value .scanned and .price
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
// (removed deletion of list item i here)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i); //<-moved to here
Now i wonder whats the correct to do this, without getting index out of range errors.
c# list
I wrote a function to go through a list and remove list items if some conditions where met. My program crashed on it, and after a while i concluded that the outer for loop, goes through all items in the list.
While at the same routine the list of item can get shorter.
// Lijst is a list of a struct that contains a value .scanned and .price
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
// (removed deletion of list item i here)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i); //<-moved to here
Now i wonder whats the correct to do this, without getting index out of range errors.
c# list
c# list
edited Nov 13 '18 at 5:53
Cœur
17.9k9107147
17.9k9107147
asked Jan 28 '16 at 9:44
user3800527user3800527
772721
772721
3
Run the loop from count to 0
– Mohit Shrivastava
Jan 28 '16 at 9:44
1
While removing items from list, you want the loop to run backwards.
– Haris
Jan 28 '16 at 9:46
1
Possible duplicate of C# List - Removing items while looping / iterating
– Rezoan
Jan 28 '16 at 9:47
1
You could achieve the same thing with a line of LINQ:list.RemoveAll(x => x.Scanned);
– TVOHM
Jan 28 '16 at 9:47
2
@TVOHM - Just to be pickylist.RemoveAll(x => x.Scanned)
isn't LINQ. It predates LINQ. It's simply an anonymous method cast as aPredicate<T>
delegate.
– Enigmativity
Jan 28 '16 at 9:50
|
show 7 more comments
3
Run the loop from count to 0
– Mohit Shrivastava
Jan 28 '16 at 9:44
1
While removing items from list, you want the loop to run backwards.
– Haris
Jan 28 '16 at 9:46
1
Possible duplicate of C# List - Removing items while looping / iterating
– Rezoan
Jan 28 '16 at 9:47
1
You could achieve the same thing with a line of LINQ:list.RemoveAll(x => x.Scanned);
– TVOHM
Jan 28 '16 at 9:47
2
@TVOHM - Just to be pickylist.RemoveAll(x => x.Scanned)
isn't LINQ. It predates LINQ. It's simply an anonymous method cast as aPredicate<T>
delegate.
– Enigmativity
Jan 28 '16 at 9:50
3
3
Run the loop from count to 0
– Mohit Shrivastava
Jan 28 '16 at 9:44
Run the loop from count to 0
– Mohit Shrivastava
Jan 28 '16 at 9:44
1
1
While removing items from list, you want the loop to run backwards.
– Haris
Jan 28 '16 at 9:46
While removing items from list, you want the loop to run backwards.
– Haris
Jan 28 '16 at 9:46
1
1
Possible duplicate of C# List - Removing items while looping / iterating
– Rezoan
Jan 28 '16 at 9:47
Possible duplicate of C# List - Removing items while looping / iterating
– Rezoan
Jan 28 '16 at 9:47
1
1
You could achieve the same thing with a line of LINQ:
list.RemoveAll(x => x.Scanned);
– TVOHM
Jan 28 '16 at 9:47
You could achieve the same thing with a line of LINQ:
list.RemoveAll(x => x.Scanned);
– TVOHM
Jan 28 '16 at 9:47
2
2
@TVOHM - Just to be picky
list.RemoveAll(x => x.Scanned)
isn't LINQ. It predates LINQ. It's simply an anonymous method cast as a Predicate<T>
delegate.– Enigmativity
Jan 28 '16 at 9:50
@TVOHM - Just to be picky
list.RemoveAll(x => x.Scanned)
isn't LINQ. It predates LINQ. It's simply an anonymous method cast as a Predicate<T>
delegate.– Enigmativity
Jan 28 '16 at 9:50
|
show 7 more comments
8 Answers
8
active
oldest
votes
You might be looking for this
for (int i = Lijst.Count - 1 ; i >= 0 ; i--)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
Question in the comment:
why would the other direction for loop work ?
Because when the loop is run in from Zero to Count There is a situation arise when the index is not available to remove and the count is still left. For example:
if you have 10 items in the List the loop starts at 0 and would remove 0,1,2,3,4 and now the item left are 5 and index is also 5 it would remove that item too. After that when loop value reaches 6 and item left is 4. Then it would create a problem. and it would throw an error. i.e. index out of range
You'll want to be starting that loop atLijst.Count-1
...
– Matthew Watson
Jan 28 '16 at 9:48
@user3800527 - It's only evaluated once at the start.
– Enigmativity
Jan 28 '16 at 9:52
no need to set thelblDebug.Text
every iteration
– Byyo
Jan 28 '16 at 10:10
@Byyo yes your right i used the debug label there as a simple way to track it.
– user3800527
Jan 28 '16 at 11:10
add a comment |
Why not direct List<T>.RemoveAll()
?
https://msdn.microsoft.com/en-us/library/wdka673a(v=vs.110).aspx
In your case
Lijst.RemoveAll(item => some condition);
E.g.
// Count all the not scanned items each of them exceeds nudMinimum.Value
lblDebug.Text = Lijst
.Where(item => !item.scanned && item.price > (int)nudMinimum.Value)
.Count()
.ToString();
// Remove all not scanned items
Lijst.RemoveAll(item => !item.scanned);
i still have to do some calculation on it, actually a bit more then in above code so i loop trough them
– user3800527
Jan 28 '16 at 9:56
@user3800527: what is the actual condition, please?
– Dmitry Bychenko
Jan 28 '16 at 9:57
add a comment |
here you go
// 1. Count items
lblDebug.Text = Lijst.Count(x => x.price > (int)nudMinimum.Value && !x.scanned).ToString();
//2. Remove items
Lijst.RemoveAll(x => !x.scanned);
add a comment |
The problems is that when you remove the element number 5, the list gets shorter and the element number 6 is now 5th, number 7 becomes 6th etc. However, if you run the loop backwards, the number is kept as expected.
for(int i = donkeys.Count - 1; i >= 0; i++)
if(donkeys[i] == some condition here)
donkeys.RemoveAt(i);
However, it's an like-a-boss approach. There are better ways. You've got the answer but I'd like to suggest a LINQ based approach.
int Totaal = Lijst
.Where(item => item.scanned)
.Where(item => item.price > (int)nudMinimum.Value)
.Count();
Lijst = Lijst.Where(item => !item.scanned).ToList()
Also, as a side note, I wonder if you find the below more readable. Consider the following different naming (both regarding the language and the capitalization).
List<Item> items = ...;
int minimum = (int)nudMinimum.Value;
int total = items
.Where(item => item.scanned)
.Where(item => item.price > minimum)
.Count();
items = items
.Where(item => !item.scanned)
.ToList();
hmm i'm not that deep into Linq, i admit that code looks nice
– user3800527
Jan 28 '16 at 10:00
@user3800527 Yeah, I kind of got that fro the loops. As I said - if you don't dare to go for LINQ (which you should because that's extremely useful and everybody uses that), just revert your loop from last element down to zero (not that it's from .Count -1 and down to i >= 0). But if I were you, I would force myself to LINQing it. Happy to be of help! :)
– Konrad Viltersten
Jan 28 '16 at 10:04
add a comment |
First You are removing the element with index i and then using it. You need to first do your process with element having index i and then remove it. Your code will look like below:
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
add a comment |
Normally if you want to remove from a list all items that match a predicate, you'd use List<T>.RemoveAll()
, for example:
List<int> test = Enumerable.Range(0, 10).ToList();
test.RemoveAll(value => value%2 == 0); // Remove all even numbers.
Console.WriteLine(string.Join(", ", test));
However, it seems you need to do some additional processing. You have two choices:
- Do it in two steps; first use
RemoveAll()
to remove unwanted items, then loop over the list to process the remaining items separately. - Loop backwards from
List.Count-1
to0
instead.
You raise a valid point but I wonder if it meets the OP's requirement on counting the total number of the removees.
– Konrad Viltersten
Jan 28 '16 at 9:58
@KonradViltersten Hence my comment about doing additional processing (see my choices 1. and 2. in the answer)
– Matthew Watson
Jan 28 '16 at 10:36
add a comment |
your code is some how is not in proper format.
first you deleted the list item and then you are trying to catch the price of that deleted item.
How can it possible.
so you can write in this way.
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
add a comment |
List<string> list = new List<string>();
list.Add("sasa");
list.Add("sames");
list.Add("samu");
list.Add("james");
for (int i = list.Count - 1; i >= 0; i--)
list.RemoveAt(i);
How to Delete Items from List
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35057865%2fcorrect-way-of-looping-through-a-list-and-remove-items%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
8 Answers
8
active
oldest
votes
8 Answers
8
active
oldest
votes
active
oldest
votes
active
oldest
votes
You might be looking for this
for (int i = Lijst.Count - 1 ; i >= 0 ; i--)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
Question in the comment:
why would the other direction for loop work ?
Because when the loop is run in from Zero to Count There is a situation arise when the index is not available to remove and the count is still left. For example:
if you have 10 items in the List the loop starts at 0 and would remove 0,1,2,3,4 and now the item left are 5 and index is also 5 it would remove that item too. After that when loop value reaches 6 and item left is 4. Then it would create a problem. and it would throw an error. i.e. index out of range
You'll want to be starting that loop atLijst.Count-1
...
– Matthew Watson
Jan 28 '16 at 9:48
@user3800527 - It's only evaluated once at the start.
– Enigmativity
Jan 28 '16 at 9:52
no need to set thelblDebug.Text
every iteration
– Byyo
Jan 28 '16 at 10:10
@Byyo yes your right i used the debug label there as a simple way to track it.
– user3800527
Jan 28 '16 at 11:10
add a comment |
You might be looking for this
for (int i = Lijst.Count - 1 ; i >= 0 ; i--)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
Question in the comment:
why would the other direction for loop work ?
Because when the loop is run in from Zero to Count There is a situation arise when the index is not available to remove and the count is still left. For example:
if you have 10 items in the List the loop starts at 0 and would remove 0,1,2,3,4 and now the item left are 5 and index is also 5 it would remove that item too. After that when loop value reaches 6 and item left is 4. Then it would create a problem. and it would throw an error. i.e. index out of range
You'll want to be starting that loop atLijst.Count-1
...
– Matthew Watson
Jan 28 '16 at 9:48
@user3800527 - It's only evaluated once at the start.
– Enigmativity
Jan 28 '16 at 9:52
no need to set thelblDebug.Text
every iteration
– Byyo
Jan 28 '16 at 10:10
@Byyo yes your right i used the debug label there as a simple way to track it.
– user3800527
Jan 28 '16 at 11:10
add a comment |
You might be looking for this
for (int i = Lijst.Count - 1 ; i >= 0 ; i--)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
Question in the comment:
why would the other direction for loop work ?
Because when the loop is run in from Zero to Count There is a situation arise when the index is not available to remove and the count is still left. For example:
if you have 10 items in the List the loop starts at 0 and would remove 0,1,2,3,4 and now the item left are 5 and index is also 5 it would remove that item too. After that when loop value reaches 6 and item left is 4. Then it would create a problem. and it would throw an error. i.e. index out of range
You might be looking for this
for (int i = Lijst.Count - 1 ; i >= 0 ; i--)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
Question in the comment:
why would the other direction for loop work ?
Because when the loop is run in from Zero to Count There is a situation arise when the index is not available to remove and the count is still left. For example:
if you have 10 items in the List the loop starts at 0 and would remove 0,1,2,3,4 and now the item left are 5 and index is also 5 it would remove that item too. After that when loop value reaches 6 and item left is 4. Then it would create a problem. and it would throw an error. i.e. index out of range
edited Jan 28 '16 at 9:59
answered Jan 28 '16 at 9:46
Mohit ShrivastavaMohit Shrivastava
11.4k52347
11.4k52347
You'll want to be starting that loop atLijst.Count-1
...
– Matthew Watson
Jan 28 '16 at 9:48
@user3800527 - It's only evaluated once at the start.
– Enigmativity
Jan 28 '16 at 9:52
no need to set thelblDebug.Text
every iteration
– Byyo
Jan 28 '16 at 10:10
@Byyo yes your right i used the debug label there as a simple way to track it.
– user3800527
Jan 28 '16 at 11:10
add a comment |
You'll want to be starting that loop atLijst.Count-1
...
– Matthew Watson
Jan 28 '16 at 9:48
@user3800527 - It's only evaluated once at the start.
– Enigmativity
Jan 28 '16 at 9:52
no need to set thelblDebug.Text
every iteration
– Byyo
Jan 28 '16 at 10:10
@Byyo yes your right i used the debug label there as a simple way to track it.
– user3800527
Jan 28 '16 at 11:10
You'll want to be starting that loop at
Lijst.Count-1
...– Matthew Watson
Jan 28 '16 at 9:48
You'll want to be starting that loop at
Lijst.Count-1
...– Matthew Watson
Jan 28 '16 at 9:48
@user3800527 - It's only evaluated once at the start.
– Enigmativity
Jan 28 '16 at 9:52
@user3800527 - It's only evaluated once at the start.
– Enigmativity
Jan 28 '16 at 9:52
no need to set the
lblDebug.Text
every iteration– Byyo
Jan 28 '16 at 10:10
no need to set the
lblDebug.Text
every iteration– Byyo
Jan 28 '16 at 10:10
@Byyo yes your right i used the debug label there as a simple way to track it.
– user3800527
Jan 28 '16 at 11:10
@Byyo yes your right i used the debug label there as a simple way to track it.
– user3800527
Jan 28 '16 at 11:10
add a comment |
Why not direct List<T>.RemoveAll()
?
https://msdn.microsoft.com/en-us/library/wdka673a(v=vs.110).aspx
In your case
Lijst.RemoveAll(item => some condition);
E.g.
// Count all the not scanned items each of them exceeds nudMinimum.Value
lblDebug.Text = Lijst
.Where(item => !item.scanned && item.price > (int)nudMinimum.Value)
.Count()
.ToString();
// Remove all not scanned items
Lijst.RemoveAll(item => !item.scanned);
i still have to do some calculation on it, actually a bit more then in above code so i loop trough them
– user3800527
Jan 28 '16 at 9:56
@user3800527: what is the actual condition, please?
– Dmitry Bychenko
Jan 28 '16 at 9:57
add a comment |
Why not direct List<T>.RemoveAll()
?
https://msdn.microsoft.com/en-us/library/wdka673a(v=vs.110).aspx
In your case
Lijst.RemoveAll(item => some condition);
E.g.
// Count all the not scanned items each of them exceeds nudMinimum.Value
lblDebug.Text = Lijst
.Where(item => !item.scanned && item.price > (int)nudMinimum.Value)
.Count()
.ToString();
// Remove all not scanned items
Lijst.RemoveAll(item => !item.scanned);
i still have to do some calculation on it, actually a bit more then in above code so i loop trough them
– user3800527
Jan 28 '16 at 9:56
@user3800527: what is the actual condition, please?
– Dmitry Bychenko
Jan 28 '16 at 9:57
add a comment |
Why not direct List<T>.RemoveAll()
?
https://msdn.microsoft.com/en-us/library/wdka673a(v=vs.110).aspx
In your case
Lijst.RemoveAll(item => some condition);
E.g.
// Count all the not scanned items each of them exceeds nudMinimum.Value
lblDebug.Text = Lijst
.Where(item => !item.scanned && item.price > (int)nudMinimum.Value)
.Count()
.ToString();
// Remove all not scanned items
Lijst.RemoveAll(item => !item.scanned);
Why not direct List<T>.RemoveAll()
?
https://msdn.microsoft.com/en-us/library/wdka673a(v=vs.110).aspx
In your case
Lijst.RemoveAll(item => some condition);
E.g.
// Count all the not scanned items each of them exceeds nudMinimum.Value
lblDebug.Text = Lijst
.Where(item => !item.scanned && item.price > (int)nudMinimum.Value)
.Count()
.ToString();
// Remove all not scanned items
Lijst.RemoveAll(item => !item.scanned);
edited Jan 28 '16 at 10:02
answered Jan 28 '16 at 9:52
Dmitry BychenkoDmitry Bychenko
107k1093133
107k1093133
i still have to do some calculation on it, actually a bit more then in above code so i loop trough them
– user3800527
Jan 28 '16 at 9:56
@user3800527: what is the actual condition, please?
– Dmitry Bychenko
Jan 28 '16 at 9:57
add a comment |
i still have to do some calculation on it, actually a bit more then in above code so i loop trough them
– user3800527
Jan 28 '16 at 9:56
@user3800527: what is the actual condition, please?
– Dmitry Bychenko
Jan 28 '16 at 9:57
i still have to do some calculation on it, actually a bit more then in above code so i loop trough them
– user3800527
Jan 28 '16 at 9:56
i still have to do some calculation on it, actually a bit more then in above code so i loop trough them
– user3800527
Jan 28 '16 at 9:56
@user3800527: what is the actual condition, please?
– Dmitry Bychenko
Jan 28 '16 at 9:57
@user3800527: what is the actual condition, please?
– Dmitry Bychenko
Jan 28 '16 at 9:57
add a comment |
here you go
// 1. Count items
lblDebug.Text = Lijst.Count(x => x.price > (int)nudMinimum.Value && !x.scanned).ToString();
//2. Remove items
Lijst.RemoveAll(x => !x.scanned);
add a comment |
here you go
// 1. Count items
lblDebug.Text = Lijst.Count(x => x.price > (int)nudMinimum.Value && !x.scanned).ToString();
//2. Remove items
Lijst.RemoveAll(x => !x.scanned);
add a comment |
here you go
// 1. Count items
lblDebug.Text = Lijst.Count(x => x.price > (int)nudMinimum.Value && !x.scanned).ToString();
//2. Remove items
Lijst.RemoveAll(x => !x.scanned);
here you go
// 1. Count items
lblDebug.Text = Lijst.Count(x => x.price > (int)nudMinimum.Value && !x.scanned).ToString();
//2. Remove items
Lijst.RemoveAll(x => !x.scanned);
answered Jan 28 '16 at 10:00
ByyoByyo
25421029
25421029
add a comment |
add a comment |
The problems is that when you remove the element number 5, the list gets shorter and the element number 6 is now 5th, number 7 becomes 6th etc. However, if you run the loop backwards, the number is kept as expected.
for(int i = donkeys.Count - 1; i >= 0; i++)
if(donkeys[i] == some condition here)
donkeys.RemoveAt(i);
However, it's an like-a-boss approach. There are better ways. You've got the answer but I'd like to suggest a LINQ based approach.
int Totaal = Lijst
.Where(item => item.scanned)
.Where(item => item.price > (int)nudMinimum.Value)
.Count();
Lijst = Lijst.Where(item => !item.scanned).ToList()
Also, as a side note, I wonder if you find the below more readable. Consider the following different naming (both regarding the language and the capitalization).
List<Item> items = ...;
int minimum = (int)nudMinimum.Value;
int total = items
.Where(item => item.scanned)
.Where(item => item.price > minimum)
.Count();
items = items
.Where(item => !item.scanned)
.ToList();
hmm i'm not that deep into Linq, i admit that code looks nice
– user3800527
Jan 28 '16 at 10:00
@user3800527 Yeah, I kind of got that fro the loops. As I said - if you don't dare to go for LINQ (which you should because that's extremely useful and everybody uses that), just revert your loop from last element down to zero (not that it's from .Count -1 and down to i >= 0). But if I were you, I would force myself to LINQing it. Happy to be of help! :)
– Konrad Viltersten
Jan 28 '16 at 10:04
add a comment |
The problems is that when you remove the element number 5, the list gets shorter and the element number 6 is now 5th, number 7 becomes 6th etc. However, if you run the loop backwards, the number is kept as expected.
for(int i = donkeys.Count - 1; i >= 0; i++)
if(donkeys[i] == some condition here)
donkeys.RemoveAt(i);
However, it's an like-a-boss approach. There are better ways. You've got the answer but I'd like to suggest a LINQ based approach.
int Totaal = Lijst
.Where(item => item.scanned)
.Where(item => item.price > (int)nudMinimum.Value)
.Count();
Lijst = Lijst.Where(item => !item.scanned).ToList()
Also, as a side note, I wonder if you find the below more readable. Consider the following different naming (both regarding the language and the capitalization).
List<Item> items = ...;
int minimum = (int)nudMinimum.Value;
int total = items
.Where(item => item.scanned)
.Where(item => item.price > minimum)
.Count();
items = items
.Where(item => !item.scanned)
.ToList();
hmm i'm not that deep into Linq, i admit that code looks nice
– user3800527
Jan 28 '16 at 10:00
@user3800527 Yeah, I kind of got that fro the loops. As I said - if you don't dare to go for LINQ (which you should because that's extremely useful and everybody uses that), just revert your loop from last element down to zero (not that it's from .Count -1 and down to i >= 0). But if I were you, I would force myself to LINQing it. Happy to be of help! :)
– Konrad Viltersten
Jan 28 '16 at 10:04
add a comment |
The problems is that when you remove the element number 5, the list gets shorter and the element number 6 is now 5th, number 7 becomes 6th etc. However, if you run the loop backwards, the number is kept as expected.
for(int i = donkeys.Count - 1; i >= 0; i++)
if(donkeys[i] == some condition here)
donkeys.RemoveAt(i);
However, it's an like-a-boss approach. There are better ways. You've got the answer but I'd like to suggest a LINQ based approach.
int Totaal = Lijst
.Where(item => item.scanned)
.Where(item => item.price > (int)nudMinimum.Value)
.Count();
Lijst = Lijst.Where(item => !item.scanned).ToList()
Also, as a side note, I wonder if you find the below more readable. Consider the following different naming (both regarding the language and the capitalization).
List<Item> items = ...;
int minimum = (int)nudMinimum.Value;
int total = items
.Where(item => item.scanned)
.Where(item => item.price > minimum)
.Count();
items = items
.Where(item => !item.scanned)
.ToList();
The problems is that when you remove the element number 5, the list gets shorter and the element number 6 is now 5th, number 7 becomes 6th etc. However, if you run the loop backwards, the number is kept as expected.
for(int i = donkeys.Count - 1; i >= 0; i++)
if(donkeys[i] == some condition here)
donkeys.RemoveAt(i);
However, it's an like-a-boss approach. There are better ways. You've got the answer but I'd like to suggest a LINQ based approach.
int Totaal = Lijst
.Where(item => item.scanned)
.Where(item => item.price > (int)nudMinimum.Value)
.Count();
Lijst = Lijst.Where(item => !item.scanned).ToList()
Also, as a side note, I wonder if you find the below more readable. Consider the following different naming (both regarding the language and the capitalization).
List<Item> items = ...;
int minimum = (int)nudMinimum.Value;
int total = items
.Where(item => item.scanned)
.Where(item => item.price > minimum)
.Count();
items = items
.Where(item => !item.scanned)
.ToList();
edited Jan 28 '16 at 10:02
answered Jan 28 '16 at 9:52
Konrad VilterstenKonrad Viltersten
12.5k31134254
12.5k31134254
hmm i'm not that deep into Linq, i admit that code looks nice
– user3800527
Jan 28 '16 at 10:00
@user3800527 Yeah, I kind of got that fro the loops. As I said - if you don't dare to go for LINQ (which you should because that's extremely useful and everybody uses that), just revert your loop from last element down to zero (not that it's from .Count -1 and down to i >= 0). But if I were you, I would force myself to LINQing it. Happy to be of help! :)
– Konrad Viltersten
Jan 28 '16 at 10:04
add a comment |
hmm i'm not that deep into Linq, i admit that code looks nice
– user3800527
Jan 28 '16 at 10:00
@user3800527 Yeah, I kind of got that fro the loops. As I said - if you don't dare to go for LINQ (which you should because that's extremely useful and everybody uses that), just revert your loop from last element down to zero (not that it's from .Count -1 and down to i >= 0). But if I were you, I would force myself to LINQing it. Happy to be of help! :)
– Konrad Viltersten
Jan 28 '16 at 10:04
hmm i'm not that deep into Linq, i admit that code looks nice
– user3800527
Jan 28 '16 at 10:00
hmm i'm not that deep into Linq, i admit that code looks nice
– user3800527
Jan 28 '16 at 10:00
@user3800527 Yeah, I kind of got that fro the loops. As I said - if you don't dare to go for LINQ (which you should because that's extremely useful and everybody uses that), just revert your loop from last element down to zero (not that it's from .Count -1 and down to i >= 0). But if I were you, I would force myself to LINQing it. Happy to be of help! :)
– Konrad Viltersten
Jan 28 '16 at 10:04
@user3800527 Yeah, I kind of got that fro the loops. As I said - if you don't dare to go for LINQ (which you should because that's extremely useful and everybody uses that), just revert your loop from last element down to zero (not that it's from .Count -1 and down to i >= 0). But if I were you, I would force myself to LINQing it. Happy to be of help! :)
– Konrad Viltersten
Jan 28 '16 at 10:04
add a comment |
First You are removing the element with index i and then using it. You need to first do your process with element having index i and then remove it. Your code will look like below:
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
add a comment |
First You are removing the element with index i and then using it. You need to first do your process with element having index i and then remove it. Your code will look like below:
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
add a comment |
First You are removing the element with index i and then using it. You need to first do your process with element having index i and then remove it. Your code will look like below:
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
First You are removing the element with index i and then using it. You need to first do your process with element having index i and then remove it. Your code will look like below:
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
answered Jan 28 '16 at 10:03
Kailash ChandelKailash Chandel
7114
7114
add a comment |
add a comment |
Normally if you want to remove from a list all items that match a predicate, you'd use List<T>.RemoveAll()
, for example:
List<int> test = Enumerable.Range(0, 10).ToList();
test.RemoveAll(value => value%2 == 0); // Remove all even numbers.
Console.WriteLine(string.Join(", ", test));
However, it seems you need to do some additional processing. You have two choices:
- Do it in two steps; first use
RemoveAll()
to remove unwanted items, then loop over the list to process the remaining items separately. - Loop backwards from
List.Count-1
to0
instead.
You raise a valid point but I wonder if it meets the OP's requirement on counting the total number of the removees.
– Konrad Viltersten
Jan 28 '16 at 9:58
@KonradViltersten Hence my comment about doing additional processing (see my choices 1. and 2. in the answer)
– Matthew Watson
Jan 28 '16 at 10:36
add a comment |
Normally if you want to remove from a list all items that match a predicate, you'd use List<T>.RemoveAll()
, for example:
List<int> test = Enumerable.Range(0, 10).ToList();
test.RemoveAll(value => value%2 == 0); // Remove all even numbers.
Console.WriteLine(string.Join(", ", test));
However, it seems you need to do some additional processing. You have two choices:
- Do it in two steps; first use
RemoveAll()
to remove unwanted items, then loop over the list to process the remaining items separately. - Loop backwards from
List.Count-1
to0
instead.
You raise a valid point but I wonder if it meets the OP's requirement on counting the total number of the removees.
– Konrad Viltersten
Jan 28 '16 at 9:58
@KonradViltersten Hence my comment about doing additional processing (see my choices 1. and 2. in the answer)
– Matthew Watson
Jan 28 '16 at 10:36
add a comment |
Normally if you want to remove from a list all items that match a predicate, you'd use List<T>.RemoveAll()
, for example:
List<int> test = Enumerable.Range(0, 10).ToList();
test.RemoveAll(value => value%2 == 0); // Remove all even numbers.
Console.WriteLine(string.Join(", ", test));
However, it seems you need to do some additional processing. You have two choices:
- Do it in two steps; first use
RemoveAll()
to remove unwanted items, then loop over the list to process the remaining items separately. - Loop backwards from
List.Count-1
to0
instead.
Normally if you want to remove from a list all items that match a predicate, you'd use List<T>.RemoveAll()
, for example:
List<int> test = Enumerable.Range(0, 10).ToList();
test.RemoveAll(value => value%2 == 0); // Remove all even numbers.
Console.WriteLine(string.Join(", ", test));
However, it seems you need to do some additional processing. You have two choices:
- Do it in two steps; first use
RemoveAll()
to remove unwanted items, then loop over the list to process the remaining items separately. - Loop backwards from
List.Count-1
to0
instead.
answered Jan 28 '16 at 9:51
Matthew WatsonMatthew Watson
72.7k692177
72.7k692177
You raise a valid point but I wonder if it meets the OP's requirement on counting the total number of the removees.
– Konrad Viltersten
Jan 28 '16 at 9:58
@KonradViltersten Hence my comment about doing additional processing (see my choices 1. and 2. in the answer)
– Matthew Watson
Jan 28 '16 at 10:36
add a comment |
You raise a valid point but I wonder if it meets the OP's requirement on counting the total number of the removees.
– Konrad Viltersten
Jan 28 '16 at 9:58
@KonradViltersten Hence my comment about doing additional processing (see my choices 1. and 2. in the answer)
– Matthew Watson
Jan 28 '16 at 10:36
You raise a valid point but I wonder if it meets the OP's requirement on counting the total number of the removees.
– Konrad Viltersten
Jan 28 '16 at 9:58
You raise a valid point but I wonder if it meets the OP's requirement on counting the total number of the removees.
– Konrad Viltersten
Jan 28 '16 at 9:58
@KonradViltersten Hence my comment about doing additional processing (see my choices 1. and 2. in the answer)
– Matthew Watson
Jan 28 '16 at 10:36
@KonradViltersten Hence my comment about doing additional processing (see my choices 1. and 2. in the answer)
– Matthew Watson
Jan 28 '16 at 10:36
add a comment |
your code is some how is not in proper format.
first you deleted the list item and then you are trying to catch the price of that deleted item.
How can it possible.
so you can write in this way.
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
add a comment |
your code is some how is not in proper format.
first you deleted the list item and then you are trying to catch the price of that deleted item.
How can it possible.
so you can write in this way.
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
add a comment |
your code is some how is not in proper format.
first you deleted the list item and then you are trying to catch the price of that deleted item.
How can it possible.
so you can write in this way.
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
your code is some how is not in proper format.
first you deleted the list item and then you are trying to catch the price of that deleted item.
How can it possible.
so you can write in this way.
for (int i = 0; i < Lijst.Count; i++)
if (Lijst[i].scanned == false)
if (Lijst[i].price > (int)nudMinimum.Value)
Totaal++;
lblDebug.Text = Totaal.ToString();
Lijst.RemoveAt(i);
answered Jan 28 '16 at 9:56
Krishna Ballavi RathKrishna Ballavi Rath
14918
14918
add a comment |
add a comment |
List<string> list = new List<string>();
list.Add("sasa");
list.Add("sames");
list.Add("samu");
list.Add("james");
for (int i = list.Count - 1; i >= 0; i--)
list.RemoveAt(i);
How to Delete Items from List
add a comment |
List<string> list = new List<string>();
list.Add("sasa");
list.Add("sames");
list.Add("samu");
list.Add("james");
for (int i = list.Count - 1; i >= 0; i--)
list.RemoveAt(i);
How to Delete Items from List
add a comment |
List<string> list = new List<string>();
list.Add("sasa");
list.Add("sames");
list.Add("samu");
list.Add("james");
for (int i = list.Count - 1; i >= 0; i--)
list.RemoveAt(i);
How to Delete Items from List
List<string> list = new List<string>();
list.Add("sasa");
list.Add("sames");
list.Add("samu");
list.Add("james");
for (int i = list.Count - 1; i >= 0; i--)
list.RemoveAt(i);
How to Delete Items from List
edited Jan 28 '16 at 10:57
answered Jan 28 '16 at 9:49
Sajidur RahmanSajidur Rahman
1115
1115
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35057865%2fcorrect-way-of-looping-through-a-list-and-remove-items%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
Run the loop from count to 0
– Mohit Shrivastava
Jan 28 '16 at 9:44
1
While removing items from list, you want the loop to run backwards.
– Haris
Jan 28 '16 at 9:46
1
Possible duplicate of C# List - Removing items while looping / iterating
– Rezoan
Jan 28 '16 at 9:47
1
You could achieve the same thing with a line of LINQ:
list.RemoveAll(x => x.Scanned);
– TVOHM
Jan 28 '16 at 9:47
2
@TVOHM - Just to be picky
list.RemoveAll(x => x.Scanned)
isn't LINQ. It predates LINQ. It's simply an anonymous method cast as aPredicate<T>
delegate.– Enigmativity
Jan 28 '16 at 9:50