Lord Vermillion Lord Vermillion - 11 months ago 68
C# Question

LINQ Where expression of unknown type

I have a database where all tables have a primary key named


I don't want to have to make multiple GetObjectForId for all my tables, i would like to make a generic method that takes IQueryable and a Type and then try to get an object from the IQueryable selection if possible.

I'm thinking something like this:

public IQueryable<Type> GetObjectForIdInCollection(IQueryable selection, Type t, int id)
return selection.Cast<T>().Where(c => c.ID == id).FirstOrDefault()

Obviously this code is totally wrong, but you get the idea what i'm trying to do.

Is this a good idea? How can i implement this method?

Answer Source

you could create a base interface, which all your entities implement:

public interface IIdObject
    int Id { get; set; }    

// ...

public T GetObjectForIdInCollection<T>(IQueryable<T> selection, int id)
    where T : IIdObject
    return selection.FirstOrDefault(c => c.Id == id);

but I don't think it is worth the effort.