Search array of a class c#

C Noob

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.

René Vogt

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).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related