I'm a beginner in C# and am doing a simple programming exercise. I would like to put the Item.price
and Item.Name
into Listbox2
.
Is it possible to put the array name into a variable and iterate with a foreach
loop? This is to avoid a very long if
, switch
, or while
loop. It could also be useful in the future if I have 40 lists.
Example
Array variable = Drinks;
foreach(Product item in variable)
{
listBox2.Items.Add(item.ProductName + item.Price);
}
PS: I've already tried using a temporary List, where I put the Drinks
into the list and call it by Product.Name
and/or Product.price
.
Could it also be more efficient? I'm very open to new ideas or approaches on how I should make my code shorter and more efficient.
public partial class Form1 : Form
{
List<Product> Drinks = new List<Product>() { new Product("Coca Cola", 1.2F), new Product("Fanta", 2.0F), new Product("Sprite", 1.5F) };
List<Product> Bread = new List<Product>() { new Product("Brown Bread", 1.2F), new Product("White Bread", 2.0F), new Product("Some otherBread", 1.5F) };
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
// instead of 40 if loops or a while loop is it possible to change the List Name with a variable and use only 1 foreach loop as the example i showed above?
if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0)
{
foreach (Product item in Drinks)
{
listBox1.Items.Add(item.ProductName);
}
}
else
{
foreach (Product item in Bread)
{
listBox1.Items.Add(item.ProductName);
}
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
// do something here
}
}
public class Product
{
private string productName;
private float price;
public Product(string productName, float price)
{
this.ProductName = productName;
this.Price = price;
}
public string ProductName
{
get { return productName; }
set { productName = value; }
}
public float Price
{
get { return price; }
set { price = value; }
}
}