0

I have a class that look like this

public class Bottle
{
    private string Brand = "";
    private string Beverage = "";
    private int Price =0;


    public Bottle(string _Brand, string _Beverage, int _Price)
    {
        Brand = _Brand;
        Beverage = _Beverage;
        Price =_Price; 
    }
}

Then i made an array of them:

 public Bottle[] Soda = new Bottle[25];

In a menu the user can chose to press 1, 2 or 3 to choose a soda to add. For example if they choose '1', they can then select a "place" in the array to store the soda. Like this:

Soda[userPlacement]= new Bottle("Cola","Soda",10);

My question is:

How do i Search that Array for Cola as example?

i've tried Array.find, and Array.indexOf but they didn't work.

stuartd
  • 70,509
  • 14
  • 132
  • 163
C Noob
  • 3
  • 3
  • 2
    Look at http://stackoverflow.com/questions/7332103/query-an-object-array-using-linq – Emil Kantis Apr 01 '16 at 10:06
  • 1
    It's easy using linq: see [this](http://stackoverflow.com/a/1175662/1997232) answer. Without linq basic idea is: iterate over array items (`for`, `foreach`) and check every item `Beverage` field value (you have to make it **public property** please). See [this](https://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx) (underscore in parameter names is kek). – Sinatr Apr 01 '16 at 10:06
  • 1
    What code did you try that "didn't work"? Its likely you'd learn a lot more by having your current attempt fixed – Sayse Apr 01 '16 at 10:10

1 Answers1

4

You can use LINQ's FirstOrDefault() like this:

Bottle cola = Soda.FirstOrDefault(b => b.Brand == "Cola");

This returns the first element in the array with Brand of "Cola" or null if there is none.


A simple straight forward version that also gives you the index could be this:

int colaIndex = -1;
for (int index = 0; index; index ++)
    if (Soda[index].Brand == "Cola")
    {
        colaIndex = index;
        break;
    }

if (colaIndex < 0)
    // no cola found
else
   // Soda[colaIndex] is your cola.

Note: as Sinatr correctly pointed out, you will need to make the Brand property public so it can be accessed by this code (alternatively you can put this code inside the Bottle class so it can access private fields).

René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • 2
    Note: `Brand` is private field (unless code belong to member of `Bottle`). – Sinatr Apr 01 '16 at 10:11
  • Thank you @RenéVogt. Is it possible to sort the Array too? If so how? – C Noob Apr 01 '16 at 12:08
  • @user6144256 yes you can sort it. There are `Sort` methods for arrays as well as `OrderBy` linq methods. You'll find a lot of threads about that on StackOverflow and the rest of the web. If they are not sufficient for you, open another question (it's too much for this thread, as I don't even know by _what_ you want to sort it). – René Vogt Apr 01 '16 at 12:10