I am trying to to create a generic cache class that will hold a list of objects,
and will expose a method that enables to check if an instance of an object is already cached based on Id property:
public class CacheService<T> where T : BaseModel
{
private List<T> _data = new List<T>();
public void Check(T obj)
{
if (_data.Contains(r => r.Id.Equals(obj.Id))
{
//Do something
}
}
}
public class BaseModel
{
public int Id { get; set; }
}
I am getting a compiler error on the Contains()
command, saying:
Cannot convert lambda expression to type 'T' because it is not a delegate type
How can I achieve my goal?
You can use Linq:
bool contains = _data.Any(r => r.Id.Equals(obj.Id));
or List.Exists
:
bool contains = _data.Exists(r => r.Id.Equals(obj.Id));
Use the LINQ function Any
instead of Contains
. For List<T>
, the Contains
method is defined to take a T
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With