Reputation: 115
I have a sorted list that contains a name and a integer value. I am new to c sharp, so I am not sure what am I doing wrong.
My code:
//first class
class Tool {
public Tool(string name, int quantity)
{
this.name = name;
this.quantity = quantity;
}
}
//main class
This is a different class (2nd class)
SortedList<Tool> gardeningTools = new SortedList<Tool>(); //error
gardeningTools.Add(new Tool("nameA", 1)); //error
Here I am trying to add some kinds of tools inside the gardening tools. The above two lines has error says "new" is not a valid keyword and both of the lines are red. I assume it's completely a wrong way to write like that. Could anyone tell me how to write it the right way?
Upvotes: 0
Views: 177
Reputation: 62542
SortedList requires two generic type arguments, the type of the key and the type of the item you're storing. In your case this might be:
SortedList<string, Tool> gardeningTools = new SortedList<string, Tool>();
Assuming that Tool
is defined something like this:
class Tool
{
public Tool(string name, int quantity)
{
this.Name = name;
this.Quantity = quantity;
}
public string Name{get;}
public int Quantity{get;}
}
Also, the Add
method takes two parameters, the key, and the value, so you want something like this:
Tool tool = new Tool("nameA", 1);
gardeningTools.Add(tool.Name, tool);
Now you can acccess them in order. For example:
foreach(var tool in gardeningTools.Values)
{
Console.WriteLine("Name = {0}, Qty = {1}", tool.Name, tool.Quantity);
}
Upvotes: 2