The following solution uses a delegate as a parameter to input some logic needed to make the method more general.
private IQueryable<SomeClass> FilterCommon(IQueryable<SomeClass> query
, Filter filter
, Func<Filter, Dictionary<Guid, string>> getDictionary
, Func<SomeClass, Guid> getKey)
{
IQueryable<SomeClass> result = null;
Dictionary<Guid, string> commonDictionary = getDictionary(filter);
if (commonDictionary != null && commonDictionary.Any())
{
result = query.Where(x => commonDictionary.ContainsKey(getKey(x)));
}
return result;
}
, Filter , :
private IQueryable<SomeClass> FilterCommon(IQueryable<SomeClass> query
, Dictionary<Guid, string> commonDictionary
, Func<SomeClass,Guid> getKey)
{
IQueryable<SomeClass> result = null;
if (commonDictionary != null && commonDictionary.Any())
{
result = query.Where(x => commonDictionary.ContainsKey(getKey(x)));
}
return result;
}
:
Filter myFilter = new Filter();
IQueryable<SomeClass> query = new Queryable();
FilterCommon(query, myFilter, x => x.Contacts, x => x.ContactID);
FilterCommon(query, myFilter.Contacts, x => x.ContactID);
FilterCommon(query, myFilter.SomethingElse, x => x.SomethingElseID);