I was looking at some Linq queries with multiple join statements. I was thinking that they could be cleaned up using extension methods that hide away the join / where statements.
For example:
(from myObject in _context.MyObject
join myObjectGroupName in _context.MyObjectGroupNames on myObject.TaskGroupNameKey equals myObjectGroupName.ReportGroupNameKey
join myObjectResourceType in _context.MyObjectResourceTypes on myObject.ResourceKey equals myObjectResourceType.ResourceKey
where myObjectGroupName.ReportGroupName.Trim().ToUpper().Equals(groupName.Trim().ToUpper()) && fileTypes.Contains(myObjectResourceType.ResourceType)
select myObject.PermissionKey);
Now becomes:
_context.MyObject.JoinWhere(_context.MyObjectGroupNames, groupName)
.JoinWhere(_context.MyObjectResourceTypes, fileTypes)
.Select(x => x.PermissionKey);
Using:
public static IQueryable<MyObject> JoinWhere(this IQueryable<MyObject> initialObject, IQueryable<MyObjectGroupName> customerReportGroupNames, string groupName)
{
return (from myObject in initialObject
join myObjectGroupName in customerReportGroupNames on myObject.TaskGroupNameKey equals myObjectGroupName.ReportGroupNameKey
where myObjectGroupName.ReportGroupName.Trim().ToUpper().Equals(groupName.Trim().ToUpper())
select myObject);
}
public static IQueryable<MyObject> JoinWhere(this IQueryable<MyObject> initialObject, IQueryable<MyObjectResourceType> myObjectResourceTypes, IEnumerable<string> types)
{
return (from myObject in initialObject
join myObjectResourceType in myObjectResourceTypes on myObject.ResourceKey equals myObjectResourceType.ResourceKey
where types.Contains(myObjectResourceType.ResourceType)
select myObject);
}
After more consideration I was wondering if it would be possible to make these methods generic:
public static IQueryable<T> JoinWhere(this IQueryable<T> initialObject, IQueryable<TJoinOn> joinOn, IEnumerable<string> types)
{
return (from myObject in initialObject
//Here //Here
join myObjectResourceType in joinOn on myObject.ResourceKey equals myObjectResourceType.ResourceKey
//Here
where types.Contains(myObjectResourceType.ResourceType)
select myObject);
}
Where I have put my comments are specific to specific objects. Could those be used generically or would I have to create an extension method for each dataObject making this WAY more work than it's really worth?