vendredi 9 décembre 2016

Generically find any items where item property value is equal using LINQ

I'm trying to implement a generic repository pattern that implements CRUD operations of generic items in an IEnumerable. I'm having issue of generically finding an item that may already be in the IEnumerable. I need to programatically pass which properties make up the 'key' or distinct record and then using LINQ do a Enumerable.Any() on the defined properties so it would see if the object already exists in the IEnumberable. Here is my code so far.

    //Generic Method
    public void AddItem(TEntity item)
    {
        var entities = GetAllItems().ToList(); //Method gets cached IEnumerable<TEntity>

        if(true)//Generically see if TEntity is already in the list based of defined properties
        {
            entities.Add(item);
        }

    }

    //Same function but non-generic
    private void AddItem(MyObject object)
    {
        var objects = GetAllItems().ToList(); //Method gets cached IEnumerable<MyObject>

        if(!objects.Any(a=> a.ID == MyObject.ID ))
        {
            objects.Add(object);
            _cache.AddReplaceCache(objects);
        }

    }





Aucun commentaire:

Enregistrer un commentaire