Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use List<T>.Contains(...)?

Tags:

c#

.net

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?

like image 239
Liel Avatar asked Jun 06 '13 22:06

Liel


2 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));
like image 126
Tim Schmelter Avatar answered Nov 11 '22 03:11

Tim Schmelter


Use the LINQ function Any instead of Contains. For List<T>, the Contains method is defined to take a T.

like image 4
Michael Gunter Avatar answered Nov 11 '22 01:11

Michael Gunter