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 ??**
}
}
Community
  • 1
  • 1
CoolArchTek
  • 3,729
  • 12
  • 47
  • 76

2 Answers2

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();
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
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++;
  }
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454