Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lambda query using generic type

I have three classes, they all have a property Date. I would like to write a generic class to return all the records for one date. Now the problem is: how can I write the lambda expression using generic type T?

The code simple is as below (i'll not compile, because "r.Date" would not working,but it's the effect that I'd like to achive)

Class GenericService<T>: IGenericService<T> where T:class
{
      ...
      readonly IGenericRepository<T> _genericRepository;
      public IEnumerable<T> GetRecordList(DateTime date)
      {
             var query=_genericRepository.FindBy(r=>r.Date=date);
}

Thank you for you help!

Regards, Léona

like image 628
Leona Avatar asked May 18 '16 08:05

Leona


1 Answers

Write an interface which has IDate and all of your entities must implement IDate and write GenericService like this :

public class GenericService<T>: IGenericService<T> where T : class, IDate
{
    readonly IGenericRepository<T> _genericRepository;
    public IEnumerable<T> GetRecordList(DateTime date)
    {
         var query=_genericRepository.FindBy(r => r.Date = date);
    }
}

public interface IDate
{
    DateTime Date{ set; get; }
}

public class Entity : IDate
{
    DateTime Date { set; get; }
}
like image 84
Kahbazi Avatar answered Oct 15 '22 23:10

Kahbazi