1

Possible Duplicate:
Remove element of a regular array

I have a method defined which returns class array. ex: Sampleclass[] The Sampleclass has properties Name, Address, City, Zip. On the client side I wanted to loop through the array and remove unwanted items. I am able to loop thru, but not sure how to remove the item.

for (int i = 0; i < Sampleclass.Length; i++)
{
if (Sampleclass[i].Address.Contains(""))
{ 
**// How to remove ??**
}
}
2
  • Already asked here: stackoverflow.com/questions/496896/… Commented Sep 22, 2011 at 15:37
  • 1
    you might want to rething the remove everything whose Address .Contains("") statement in there Commented Sep 22, 2011 at 15:39

2 Answers 2

5

Arrays are fixed size and don't allow you to remove items once allocated - for this you can use List<T> instead. Alternatively you could use Linq to filter and project to a new array:

var filteredSampleArray = Sampleclass.Where( x => !x.Address.Contains(someString))
                                     .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

It's not possible to remove from an array in this fashion. Arrays are statically allocated collections who's size doesn't change. You need to use a collection like List<T> instead. With List<T> you could do the following

var i = 0;
while (i < Sampleclass.Count) {
  if (Sampleclass[i].Address.Contains("")) {
    Sampleclass.RemoveAt(i);
  } else {
    i++;
  }
}

2 Comments

@StriplingWarrior updated to reflect OP should be using List<T> vs. an array
I don't see a 'RemoveAt' option. Don't know why!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.