-3

I have an object array that I add objects into (soda drinks). As I am now to build in also a method to remove specific objects from the array, I want to make sure that the objects are always placed before any empty spots in the array (sorting null to last).

How do I most efficiently sort nulls/empty spots to last in an array like this?

object[] bottleVector = new object[24];

// Constructor within class Sodacrate
class Soda
    {
        //CLASS VARIABLES
        public string name;
        public double price;

        //CLASS CONSTRUCTOR
        public Soda(string _name, double _price)
        {
            name = _name;
            price = _price;
        }
    }
....
// Later in the code
public void add_soda()
{
    //This is where I need help
    bottles.Sort()
}
kayess
  • 3,384
  • 9
  • 28
  • 45
Daniel Slätt
  • 751
  • 2
  • 15
  • 28
  • 2
    Where do you have a vector? Do you mean the array? Why are you using the `object` type? And what is `bottles`? Please provide an actual [mcve] – UnholySheep Feb 01 '18 at 14:51
  • 2
    Why are you using an array of Object and not a `List`? You could leverage LINQ to do `OrderBy()` Why does your Soda object use fields and not properties? Also, I don't see a single Vector object. Are you using the wrong word? An array is not a vector... – maccettura Feb 01 '18 at 14:52
  • 1
    [`List`](https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx) is usually the correct type for a dynamic-length ordered sequence of homogeneous elements in C#; `T[]` is not and `object[]` is _definitely_ not. – TypeIA Feb 01 '18 at 14:54
  • If you specify what you want to achieve with that code we can help with some advice but first check out some data structures and be sure that you can`t find the structure which will fit in you solution before you ask questions here. – Люсиен Лозанов Feb 01 '18 at 14:55
  • 1
    @BobbyA this question is a poor fit over there for the same reasons as it is here. Please abstain of recommending sites you're not familiar with. See also: **[What goes on Software Engineering (previously known as Programmers)? A guide for Stack Overflow](https://softwareengineering.meta.stackexchange.com/q/7182/31260)** – gnat Feb 01 '18 at 17:00
  • @gnat I should have been explicit, but I was implying the question would also have to be reworded, if my assumption about his question was correct. – BobbyA Feb 01 '18 at 19:38

2 Answers2

3

It seems that you are looking for in place sorting.

If vector (which is C++, not C# conception) means array, Soda[] then:

 Soda[] bottles = ...

 //TODO: lamda (left, right) => should return -1, 0 or 1
 // depeding on if left < right, left == right, left > right
 // sample below shows sorting by price
 Array.Sort<Soda>(bottles, (left, right) => left.price.CompareTo(right.price));

If vector is List<T> then (preferred way, since you want to remove items):

 List<Soda> bottles = ...

 //TODO: lamda (left, right) => should return -1, 0 or 1
 // depeding on if left < right, left == right, left > right
 // sample below shows sorting by price
 list.Sort((left, right) => left.price.CompareTo(right.price));

Finally, you can implement IComparable<Soda> interface within Soda class (if you have just one default way of sorting Soda class instances):

 public class Soda: IComparable<Soda> {
   ...

   public int CompareTo(Soda other) {
     if (object.ReferenceEquals(this, other))
       return 0;
     else if (null == other)
       return 1;

     //TODO: return -1, 0, 1 depending on if this <=> other
     return price.CompareTo(other.price);
   }
 } 

Then either:

 Soda[] bottles = ...

 Array.Sort(bottle);

Or (a better approach):

 List<Soda> bottles = ...

 bottles.Sort();
kayess
  • 3,384
  • 9
  • 28
  • 45
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 2
    Just because the word *vector* was mentioned, does not change the intended language of discussion. Your edit that approved the tag change should not have removed the `c#` tag, and your additional edit of italicizing text would have been rejected because it offers no improvement. – Blue Feb 01 '18 at 16:01
  • @FrankerZ thank you for removing the `c++` tag, I restored the C# tag and just had a brain fart on removing the c++ – maccettura Feb 01 '18 at 16:15
2

I see a lot of issues with your code.

  • An array is not a vector. They are two completely different things (from two completely different languages). If you want an "array" that can change in size, in C# that means you typically want a List. A List can be created without knowing the ultimate size of it, it can be dynamically added to which is likely what you want. You also dont have to worry about what order they are added in because it only ever has what you have added.
  • Your array is an array of object, not an array of Soda like it should be. You always want to specify the type so that you can access members of the class. If your List is of type object, you cannot access the members without casting.
  • Your Soda class is using fields instead of properties. You likely want to use properties.
  • Never use double for money values, this is what decimal is for.

Heres what your code should be:

List<Soda> sodaList = new List<Soda>();

// Constructor within class Sodacrate
public class Soda
{
    //CLASS PROPERTIES
    public string Name {get; set;}
    public decimal Price {get; set;}

    //CLASS CONSTRUCTOR
    public Soda(string name, decimal price)
    {
        Name = name;
        Price = price;
    }
}

As for the "Sorting" aspect of your question. To me it reads that you want your array sorted so that when you add an item it puts it at a specific position in the array. If you use List<Soda> you dont have to worry about what position its inserted at because there is no predefined size, its just added in the order that you add it. If you do need to sort by price or name however, you could easily leverage LINQ and use OrderBy():

//Orders by Price in ascending order
sodaList = sodaList.OrderBy(x => x.Price);
maccettura
  • 10,514
  • 3
  • 28
  • 35
  • 3
    Please update your answer that the original edit contained asking about vectors rather than rolling back. You can even link to the earlier revision. – kayess Feb 01 '18 at 16:18
  • @kayess your edits are improper. You are changing the OP's original question. – maccettura Feb 01 '18 at 16:19
  • 2
    Not at all, since OP is using it as a variable name and not as a _type_ – kayess Feb 01 '18 at 16:20
  • 1
    @kayess OP might come from a C++ background where a vector is an array that changes size. Changing from vector to array in the edits _completely_ changes the meaning of what they are asking – maccettura Feb 01 '18 at 16:21
  • 2
    @maccettura C# does not have vectors, C# has Lists. OP calling a List a vector and naming the object `bottleVector` does not make it a vector. I agree that using the word "array" might be problematic, but the question certainly should have been edited to clarify that OP is not actually working with vectors in C#. – TylerH Feb 01 '18 at 16:22