开发者

c# Array or Collection

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 wi开发者_运维技巧thout knowing the total number of rows that I will have? Or should I use a collection can those be multidimensional?

Thanks


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


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.


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;


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});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜