简体   繁体   中英

C# , make method more generic

Please look at the following method:

internal IEnumerable<Query> FilterOnUserInvolvement(IEnumerable<Query> input)
{
    var user = _userManager.GetUserByADName(_user.Identity.Name);
    if (_userManager.IsUserAdministrator(user) || _userManager.IsUserStaff(user))
    {
        return input;
    }
    else
    {
        using (var context = new QAContext())
        {
            var involvedQueries = context.UserInvolvement.Where(x => x.UserID == user.ID).Select(x => x.QueryID).ToList();
            return input.Where(i => involvedQueries.Contains(i.ID));
        }
    }
}

Now this method takes IEnumerable<Query> and returns the same.

Actually the functionality of this method could be applied to any IEnumerable<Type> that holds ID.

How can I rewrite this query, using generics so it can be called with another Type that holds ID?

Just restrict your T to a type that contains ID :

internal IEnumerable<T> FilterOnUserInvolvement<T>(IEnumerable<T> input) where T : ISomeInterfaceWithId
{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM