Carter
Carter

Reputation: 57

How to remove elements from array without using System.Collection or LINQ in C#?

I've got a problem when "removing" elements from array in C#, but without using System.Collection and LINQ.

for example:

I have a Product class which contains fields p_name, p_number and is_useful (this value is true by default);

I also have a ShoppingCart class which contains field market_name, products_quantity and Products (the type is Product[], storing all products)

Suppose I've created four Product objects p1, p2 , p3, p4, and then created one ShoppingCart object sc with a fixed length Products[4] ( p1, p2, p3 & p4 are stored it);

Then I set the is_useful value of p2 to false, so p2 in the Products[4] will become useless for the ShoppingCart, and it needs to be removed from Products[4].

is it possible that remove p2 from Products[4], and the length of this array will be reduced to 3 (Products[3] with p1, p3 & p4 inside), and it still belongs to the Shoppingcart object sc (like when I use sc.Products to get the all products, it will refer to the new Products[3])?

Thanks!

Upvotes: 2

Views: 911

Answers (2)

Manish Kumar
Manish Kumar

Reputation: 113

Here are the way of top of my head:

  1. setting the element to null (and moving it to end : optional), and handling the null value in you access code. (you can use a wrapper method/class for this too) adv: this doesn't involve in any object recreations, reallocation.

  2. Array.Resize() : involves array reallocation, but if your array is short and the operation is very in-frequent you can live with this solution. http://msdn.microsoft.com/en-us/library/bb348051.aspx)

  3. Using Collection: Ideal for dynamic sized lists/arrays.

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Use Array.Resize static method:

  • replace element you'd like to remove with the last one
  • call Array.Resize with your array reference and length set to current length - 1
// let's say you'd like to remove the i-th element
//
// You don't have to move Products[i] to the last position,
// because it will be removed anyway.
sc.Products[i] = sc.Products[sc.Products.Length - 1];
// Call Array.Resize to change array size
Array.Resize(sc.Products, sc.Products.Length - 1);

Upvotes: 5

Related Questions