use object in c# dictionary
I use dictionary in my program like this
Dictionary<string, List<Term>>
which Term is object from class has two fields (name , id) I need add n开发者_C百科ew object into dictionary where the name of new object is not found in the dictionary... if the field name in new object is existent as name of old object I will not add it.. can you help me the code I use is
foreach (string term in terms)
{
if (!dictionary.ContainsKey(term))
{
dictionary.Add(term, new List<Term>());
}
Term TT=new Term(i,name);
if (!dictionary[term].Contains(TT))
{
dictionary[term].Add(TT);
}
this code dosn't work exactly..
The problem is here:
if (!dictionary[term].Contains(TT))
{
dictionary[term].Add(TT);
}
The default behavior of List.Contains
if class Term
does not implement IEquatable<Term>
is to check for reference equality. Since the object you just constructed cannot already be in the list, Contains
will always return false
and the new Term
will always be added.
One good solution would be to implement IEquatable<Term>
in Term
and specify the criteria you want for equality in the IEquatable<Term>.Equals
method.
Another solution (which is probably less desirable because it will only help this particular piece of code to work) is to change the test to
// Change the t.name == TT.name test to whatever your idea
// of "term X equals term Y" is
if (dictionary[term].FindIndex(t => t.name == TT.name) == -1)
{
dictionary[term].Add(TT);
}
I assume a term object is identified by it's id. So you either need to implement IEquatable<Term>
on the term class or look for the term with the right id like this:
if (!dictionary[term].Any(x => x.Id == TT.id))
{
dictionary[term].Add(TT);
}
Note: Any is a Linq extension method, so you need to add using System.Linq;
static void Main(string[] args)
{
//Database producten
Dictionary<string, double> producten = new Dictionary<string, double>();
Console.WriteLine("Dit zijn de beschikbare producten");
producten.Add("T-shirt", 45.35);
Console.WriteLine("T-shirt");
producten.Add("trui", 25.50);
Console.WriteLine("trui");
producten.Add("broek" , 90);
Console.WriteLine("broek");
//Einde database
//Console.WriteLine(producten["trui"]);
double tot = 0;
bool boot = true;
Dictionary<string, int> winkelmandje = new Dictionary<string, int>();
while (boot)
{
Console.WriteLine("Wilt u een product toevoegen?, ja of nee?");
string answer = Console.ReadLine();
if (answer == "ja")
{
Console.WriteLine("Geef de naam van het product?:");
string naam = Console.ReadLine();
Console.WriteLine("Hoeveel aantallen wenst u van dit product?:");
int inthvl = Convert.ToInt32(Console.ReadLine());
winkelmandje.Add(naam, inthvl);
}
if (answer == "nee")
{
foreach(KeyValuePair<string, int> product in winkelmandje)
{
if (producten.ContainsKey(product.Key))
{
tot = tot + producten[product.Key] * product.Value;
}
else
{
Console.WriteLine("Dit product verkopen wij niet.");
}
}
boot = true;
Console.WriteLine("Gelieve " + tot + " euro te betalen.");
}
精彩评论