3

How would you approach this? I have a list of data that has two things that need to be stored price and item, is there anyway to store this in an array without knowing the total number of rows that I will have? Or should I use a collection can those be multidimensional?

Thanks

4

4 回答 4

6

Yes - I'd recommend you look into a generic list. Using this you can model your data and store as many items as you like.

For example

  public class PricedItem
    {
        public decimal Price { get; set; }
        public object Item { get; set; }
    }

These could then be stored/retrieved in a List<PricedItem> - or as 'list of priced items'.

Hope that helps

于 2011-02-21T17:08:56.137 回答
2

Sounds like you should use the "dictionary" generic collection, with for example the item id as a key and price as a value.

If you want to have more information in the collection you can even store instances of a item class in the dictionary. So if your item class has properties like id, name, description, price, you can do things like

Dictionary<int, item> items = new Dictionary<int, item>();
items.add(myitem.id, myitem);

Then for any item ID you could access the information like this

string description = items[id].description; 
decimal price = items[id].price;
于 2011-02-21T17:11:00.767 回答
2

Use a List<> of some compound type that contains your price and item. There is a built-in structure type called a KeyValuePair<> that will allow you to store strongly-typed Keys (items) and Values (prices). A List<KeyValuePair<string, string>> and some Linq will allow you to perform lookups based on row, key or value. If you want to look up prices based on the item, a Dictionary is a collection of KeyValuePairs accessible by Key, that can provide similar functionality but uses a different internal structure, so access by row number isn't available.

于 2011-02-21T17:13:36.620 回答
0

you could have

struct Item
{
    float Price;
    string ItemName;
}

and

List<Item> items = new List<Item>();
items.Add(new Item{Name="item1", Price=19.99});
于 2011-02-21T17:12:29.577 回答