Using one Func <T, bool> with Where () and inheritance

I am trying to use one definition Func<T,bool>to process a class and its descendant. This is what I have:

Func<Job, bool> ValidJob =
        j => !j.Deleted && !j.OnHold && j.PostDate <= DateTime.Now && j.ExpireDate > DateTime.Now;

public class JobExtended : Job { }

So, considering that the following works:

IQueryable<Job> jobs = ...
jobs.Where(ValidJob);

However, the following:

IQueryable<JobExtended> jobs = ...
jobs.Where(ValidJob);

I wonder if there can be one in this situation Func<T,bool>, and if so, how? I tried to specify type arguments as suggested, but I had no luck.

+3
source share
2 answers

This will work in C # 4, where delegates have common covariance and contravariance, but not earlier than this. However, you can easily use an existing delegate with C # 2 onwards:

jobs.Where(new Func<JobExtended, bool>(ValidJob));
+6
source

: :

public static bool ValidJob<T>(T j) where T : Job
{
    return
        !j.Deleted && 
        !j.OnHold &&
        j.PostDate <= DateTime.Now &&
        j.ExpireDate > DateTime.Now;
}

:

IQueryable<Job> jobs = ...
jobs.Where(ValidJob);

IQueryable<JobExtended> jobs = ...
jobs.Where(ValidJob);
+3

Source: https://habr.com/ru/post/1714439/


All Articles