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,609
  • 12
  • 45
  • 75

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
  • 153,880
  • 28
  • 280
  • 327
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
  • 703,665
  • 143
  • 1,211
  • 1,438