Method
Method

Reputation: 143

editing the iteration value in a foreach loop

Situation

I'm trying to design a simple remove method that deletes an object if the incoming ID parameter matches an ID on record:

For instance, if a Race had an ID "123" then it would find the race that had the ID "123" and set it to null, thus removing it.

I've looked at a few methods online and yeah, it seems to be a recurring problem with foreach specifically, but I'd really like to do it this way if possible.

    public void removeRace(string RaceID)
            {

                foreach (BaseRace br in races)
                {
                    //if the ID entered into this method as a parameter matches an ID on record.
                if (RaceID == br.raceID)
                {
                    //set the current ID to null, thus deleting the record.
                    //br = null;

                }
            }
        }

Problem

My code, specifically br = null; doesn't work, since the foreach loop won't let me edit the iterator.

how can I solve this issue in another way?

Upvotes: 0

Views: 44

Answers (2)

Greg
Greg

Reputation: 11480

You should be able to do it fairly simple with Linq.

var filter = races.Where(d => d.Id != value).ToList();

That would account for a single value, which it would remove. You could also do a projection, with a SelectMany and Where culmination that would also filter. Would need some more context.

This approach may not be ideal, Marcin's approach may be more ideal. Need more context though.

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

List<T> already provides method to do that:

public void removeRace(string RaceID)
{
    races.RemoveAll(br => RaceID == br.raceID);
}

If you really don't want to use it you'd have to use a for loop instead of foreach.

Upvotes: 4

Related Questions