Home > OS >  Adding value to strings in an array
Adding value to strings in an array

Time:10-11

Is it possible to add int/uint values to each of the string array strings("Item1") instead of the default ones 0-5 in this case

                string[] items = new string[5]
            {
                "Item1",
                "Item2",
                "Item3",
                "Item4",
                "Item5"
            };

Im trying to add a value to each of the ("Item1","Item2"...) inside the array is that possible?

CodePudding user response:

Not sure if this is what you're looking for, but why not use a Dictionary?

Dictionary<string, int> items = new Dictionary<string, int>();

items.Add("Item1", 1001);
items.Add("Item2", 1002);
items.Add("Item3", 1003);
items.Add("Item4", 1004);
items.Add("Item5", 1005);

You can then get the ID corresponding to an Item as follows

items["Item1"]; //Should give you 1001

Example

foreach(var item in items.Keys){
    Console.WriteLine (item   ":"   items[item]);
}

Output

Item1:1001
Item2:1002
Item3:1003
Item4:1004
Item5:1005

CodePudding user response:

You should try to use classes :

class Item
{
     int ItemId {get; set;}
     string ItemName {get;set;}
}

and then use it like this :

List<Item> items = new List<Item>();
item.Add(new Item{ ItemId = 1,ItemName = "First"});
item.Add(new Item{ ItemId = 2,ItemName = "Second"});

CodePudding user response:

You could also use a dictionary.

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("Item1", 1000);

If you want to initialize the items more easily you can declare it in one line like this:

Dictionary<string, int> dict = new Dictionary<string, int>(){{"Item1", 1},{"Item2", 2}};
  •  Tags:  
  • c#
  • Related