C# convert System.Func<Tderived, bool> to System/Func<Tbase, bool>

I've googled but couldn't find satisfactory answers. I'm basically trying to get this code to work:

public List<WordEntry> WordDataBase = new List<WordEntry>();
public List<CharacterEntry> CharacterDataBase = new List<CharacterEntry>();

public List<Entry> SelectWhere<T>(System.Func<T, bool> predicate) where T : Entry
{
    if (typeof(T) == typeof(WordEntry))
        return WordDataBase.Where(predicate);
    else if (typeof(T) == typeof(CharacterEntry))
        return CharacterDataBase.Where(predicate);
    else
        return null;
} 

In this sample, both WordEntry and CharacterEntry are derived from Entry. I get the compiler errors:

Error   CS1503  Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<WordEntry, int, bool>'   

and

Error   CS1503  Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<CharacterEntry, int, bool>'

Hopefully you can help me with this. Thanks in advance

Jon Skeet
people
quotationmark

Basically, you just need to cast - the language rules don't allow the compiler to take the if statement into account when it thinks about the types involved. Note that you also need to call ToList<Entry>(), specifying the type argument to avoid getting a List<WordEntry> or List<CharacterEntry>:

public List<Entry> SelectWhere<T>(Func<T, bool> predicate) where T : Entry
{
    if (typeof(T) == typeof(WordEntry))
        return WordDataBase
            .Where((Func<WordEntry, bool>) predicate)
            .ToList<Entry>();
    else if (typeof(T) == typeof(CharacterEntry))
        return CharacterDataBase
            .Where((Func<CharacterEntry, bool>) predicate)
            .ToList<Entry>();
    else
        return null;
}

I'd suggest that rather than making this generic though, you might want to just have two different methods instead. It doesn't feel like it's really a generic method, given that it only works with two very specific types.

people

See more on this question at Stackoverflow