Reputation: 7
I have a problem about my object type. The object i got Caegory. When a the list contains it object must not be added however the code bellow adds it and second time i send the same object it does not add. So i think it is about casting bu even i do casting it worked as i described before. I can solve it with for loops but i want to learn why this is not working.
private List<Category> choosenCategoriesList = new List<Category>(); //categoriesList to be used in categorization stage
private List<Category> categoriesList = new List<Category>();
Category categ = categoriesList.Find(x => x.name == cdm_comboBox.SelectedItem.ToString());
if (!choosenCategoriesList.Contains(((Category)categ)))
{
choosenCategoriesList.Add(categ);
categorizationFinished = false;
}
Upvotes: 0
Views: 91
Reputation: 179
In order to use the List.contains()
you need to implement the IEquatable
interface and override the Equals
function for your class.
public class Category: IEquatable<Category>
{
string name;
int id;
public override bool Equals(object obj)
{
if (obj == null) return false;
Category objAsCategory = obj as Category;
if (objAsCategory == null) return false;
else return Equals(objAsCategory);
}
public bool Equals(Category other)
{
if (other == null) return false;
return (this.id.Equals(other.id));
}
}
This tells your object what makes it a duplicate when Equals is called based on your description instead of needing to be a exact reference of the object.
A other option is the use List..Exists((x => x.name == "name");
This works the same a find but will return a Boolean instead of the found object.
more info on this can be found here: https://msdn.microsoft.com/en-us/library/bhkz42b3(v=vs.110).aspx
Upvotes: 1
Reputation: 11
This is may be because you are getting item in categ as selcted item. second time may be item is not there so its empty and not adding to the list
Upvotes: 0