Search code examples
c#mvvmcollectionsduplicatesirepository

How to prevent duplicate items from being added to an IRepository?


I've used an IRepository to store a subject and score pair in a repository. Now I'm trying to figure out how to prevent duplicate subject names, from being added to that repository.

I tried the following solution using a statement to check if the repositry already contains the subject name:

if (_repository.Count <= 5 && (!_repository.Collection.Contains(SelectedSubjectName))) 
{
    _repository.Add(new ScoreModel() {Subject = SelectedSubjectName, Points = SelectedPoints});
    CalculateLeavingCertPoints();
}

But I get an overload mismatch error stating that:

Error 1 The best overloaded method match for 'System.Collections.ObjectModel.Collection<LC_Points.Model.ScoreModel>.Contains(LC_Points.Model.ScoreModel) has some invalid arguments

and

Error 2 Argument 1: cannot convert from 'string' to 'LC_Points.Model.ScoreModel'

Does anyone have an idea how to fix the statement arguments?

I can see that the SubjectName is the string type, and that cannot be passed as an argument according to the second error. So I tried ScoreModel.Subject but that wasn't allowed by the compiler. Any advice appreciated.

This is the ScoreModel for reference:

http://hastebin.com/emagojojug.vala


Solution

  • If _repository.Collection is a collection of ScoreModel objects, you cannot do a Contains with a string. You need to do the check with the specific property you want to avoid duplicates on.

    So, replace this part:

    !_repository.Collection.Contains(SelectedSubjectName)
    

    by

    _repository.Collection.All(s=>s.Subject != SelectedSubjectName)
    

    This will be true if all existing subjects are different from the new subject name. I believe this is what you are after.