How to delete items from list using foreach

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • EMILO9
    New Member
    • Aug 2019
    • 1

    How to delete items from list using foreach

    Code:
    if (r == "delete"){
    Console.Write("Who do you want to remove from the list?: ");
    int x = Convert.ToInt32(Console.ReadLine());
    foreach (var person in Person) {
    if (x == person.Id) Person.RemoveAt(x);
    }
    }
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 656

    #2
    - 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:
    Code:
     IF CHOICE == 'DELETE' 
       x = What to delete
       for (int i = 0; i < list.Count; i++){
        if( x == list[i]){
           list.RemoveAt[i];
        }
       }
    - Index can also be obtained using IndexOf method, but it returns the first index of an item if found in the list.

    Comment

    • gosai jahnvi
      New Member
      • Apr 2019
      • 22

      #3
      You can attempt this code, and I hope it helps you.
      Code:
      var list = new List<int>(Enumerable.Range(1, 10));
      for (int i = list.Count - 1; i >= 0; i--)
      {
          if (list[i] > 5)
              list.RemoveAt(i);
      }
      list.ForEach(i => Console.WriteLine(i));
      thank you.

      Comment

      Working...