1

I'm a new student to C# and I have a project I'm kind of stuck on. I need to create a method that uses an index\ID number to find and remove information on an employee.

This uses a structure, "Employee" and a list, "employees" and I'm just lost as to how I'm supposed to remove the all the information from the list. Do I set all the field values, including strings, to 0?

The following are the instructions I was given for this method -- "c) DeleteEmployee( ) Takes the index of the employee as a parameter. Remove the employee with the parameter value"

private int DeleteEmployee (int index)
    {
        foreach (Employee E in employees)
        {
            if (index == E.id) {}
// i'm just stuck on what to do from this point       
        }

// return zero is just here temporarily
        return 0;
    }
aBoy
  • 35
  • 1
  • 5
  • What Type of object is `employees`? – hatchet - done with SOverflow Apr 07 '17 at 23:28
  • employees is a list of a structure i made -- "List employees = new List();" with the structure being "Employee" with a number of string,double, and int fields. – aBoy Apr 07 '17 at 23:35
  • :Must you "create" a method as LINQ already has methods to find results WHERE something equals something. But like Sergey says you cannot modify that list but would need to create a newList. You can do this by a statement like this `myList = myList.Where(x => x.Id != 1).ToList()`; – Edward Apr 07 '17 at 23:51
  • While I feel solving this might be unhelpful in the long run since it's an assignment, I do want to point out that you can't remove an element from a list in a foreach. – Nabren Apr 08 '17 at 00:54

1 Answers1

6

It's not allowed to modify sequence which you are enumerating in foreach loop. If you want to remove item from list by index use RemoveAt:

employees.RemoveAt(index);

if you want to remove items by some criteria, use RemoveAll

employees.RemoveAll(e => e.id == index)

how I'm supposed to remove the all the information from the list. Do I set all the field values, including strings, to 0?

You should understand, that employee list is just an array which holds references to employee objects (you can think about reference as an address in memory where object's data is located). Modifying employee fields will not remove reference from list. List still will be referencing same employee object, but with all fields set to default values. In order to remove employee from list, you should remove reference to employee object. That can be achieved with Remove, RemoveAt, or RemoveAll methods.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459