Create a new element in an array in c #

0

I would like you to help me how I could generate a new object in the Product list, it's a simple CRUD

using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ProductsApp.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[]
            {
                new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1  },
                new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.5M  },
                new Product { Id = 3, Name = "Hammer", Category = "Hardwarw", Price = 16.99M  }
            };



        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }


    }
}
    
asked by Rodrigo Ayala 25.02.2017 в 10:29
source

1 answer

2

Arrays are not suitable for adding and removing elements at runtime. If you need that type of behavior, it is best to use another type of data, for example in your case List<Product> .

If you still insist on using arrays, you can use Array.Resize that allows you to make the array bigger and then add the new element, although you must bear in mind that it is quite expensive and that the array is actually rebuilt .

Array.Resize(ref products, products.Length + 1);
products[products.Length - 1] = product;
    
answered by 27.02.2017 в 09:12