Updating cache object that contains collection of employees

1.4k views Asked by At

I have a collection of Employees that I stored inside MemoryCache.Now after update of particular employee details, I want to update the same cache object with updated employee details. Something like that:

var AllEmployees= cache.Get("AllEmployees");
if(AllEmployees != null)
{
       var empToUpdate = AllEmployees.FirstOrDefault(i => i.EmpId== Employee.EmpId);
       if (empToUpdate != null)
       {
           AllEmployees.Remove(empToUpdate );
           AllEmployees.add(empToUpdate ); 
      }
}

but since cache is memory cache and it has cached IEnumerable<Employee>,i am not able to directly manipulate cache object.I am not able to call these methods FirstOrDefault,Remove,Add

1

There are 1 answers

1
BudBrot On BEST ANSWER

As mentioned in my comment i cant see a reason to no use FirstOrDefault. IEnumerables are not ment to be modified. So you have to go a heavy, performanceunfirendly way and create a new IEnumerable without a specific item (IENumerable.Except(array of items to exclude)) then yo gonna concat it with another sequenze, which contains your new element to add.

   var empToUpdate = AllEmployees.FirstOrDefault(i => i.EmpId== Employee.EmpId);
   if (empToUpdate != null)
   {
      AllEmployees = AllEmployees.Except(new[]{empToUpdate}).Concat(new[] { empToUpdate});
  }

Anyways i dont see a sense in this code, cause you are removing the object and immediatly add it again.