Is it possible to use List <T> .Contains (...)?
I am trying to create a general cache class that will contain a list of objects
, and will expose a method that allows you to check whether the object instance has already been cached based on the 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 get a compiler error in the Contains() command saying:
Cannot convert lambda expression to type 'T' because it is not a delegate type
How can I achieve my goal?
+7
Liel
source share2 answers
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)); +18
Tim schmelter
source shareUse the LINQ Any function instead of Contains . For List<T> the Contains method is defined as a T
+4
Michael gunter
source share