tags:

views:

370

answers:

3

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.

+3  A: 

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.

Neil Barnwell
You really don't want to call it on a *new* list though... fieldRow.RemoveAll is what you mean, I think :)
Jon Skeet
Oops, well spotted. That's what I get for switching to VS to get syntax colouring and intellisense!
Neil Barnwell
+7  A: 
public class Field
{
  List<FieldRow> fieldRow;

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

public class FieldRow
{
  public int key;
}
Chris Doggett
+1  A: 

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 :-)

driis