By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,251 Members | 2,760 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,251 IT Pros & Developers. It's quick & easy.

How to delete items from list using foreach

P: 1
Expand|Select|Wrap|Line Numbers
  1. if (r == "delete"){
  2. Console.Write("Who do you want to remove from the list?: ");
  3. int x = Convert.ToInt32(Console.ReadLine());
  4. foreach (var person in Person) {
  5. if (x == person.Id) Person.RemoveAt(x);
  6. }
  7. }
1 Week Ago #1
Share this Question
Share on Google+
2 Replies


dev7060
P: 90
- foreach loop iterates through elements but for performing deletion using RemoveAt(), index must be known.

- for loop can be used with RemoveAt() for such purpose. Here's the pseudo code/algo:
Expand|Select|Wrap|Line Numbers
  1.  IF CHOICE == 'DELETE' 
  2.    x = What to delete
  3.    for (int i = 0; i < list.Count; i++){
  4.     if( x == list[i]){
  5.        list.RemoveAt[i];
  6.     }
  7.    }
  8.  
- Index can also be obtained using IndexOf method, but it returns the first index of an item if found in the list.
1 Week Ago #2

P: 22
You can attempt this code, and I hope it helps you.
Expand|Select|Wrap|Line Numbers
  1. var list = new List<int>(Enumerable.Range(1, 10));
  2. for (int i = list.Count - 1; i >= 0; i--)
  3. {
  4.     if (list[i] > 5)
  5.         list.RemoveAt(i);
  6. }
  7. list.ForEach(i => Console.WriteLine(i));
thank you.
3 Days Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.