DotnetDude
DotnetDude

Reputation: 11817

Removing an item from a list - C#

I have rather a complex datastructure. The simple version looks like this:

public class Field
{

  List<FieldRow> fieldRow;

  //I want to write a delete that iterates and deletes given the key 
  //(Use Linq?)
  public void DeleteByKey(int key)
  {
    //Do Remove
  }
}

public class FieldRow
{
  public int key;
}

Any help in implementing Delete is appreciated.

Upvotes: 0

Views: 3333

Answers (3)

driis
driis

Reputation: 164341

You could find the index of the field you need to remove and use the RemoveAt method on List.

I will add an example in a minute. Nevermind, the suggestion to use RemoveAll with a predicate seems to be a better option :-)

Upvotes: 1

Chris Doggett
Chris Doggett

Reputation: 20787

public class Field
{
  List<FieldRow> fieldRow;

  public void DeleteByKey(int key)
  {
    fieldRow.RemoveAll(row => key == row.key);
  }
}

public class FieldRow
{
  public int key;
}

Upvotes: 7

Neil Barnwell
Neil Barnwell

Reputation: 42175

List<T>().RemoveAll() will do what you want.

You give it a Predicate delegate type, that is executed for each item, like a where clause:

fieldRow.RemoveAll(item => item.Key == key);

However, you might want to consider storing the data in a Dictionary<int, FieldRow>. That way you can access the dictionary/map directly by key. This would improve performance.

Upvotes: 3

Related Questions