Open
Description
It would be nice to have a utility method for a left join that merges the lists using an expression. Instead of returning an enumerable of items that matches the predicate, it should also be possible to return only the first match.
The following pattern often occurs in our solution:
fields.GroupJoin<FieldDto, Caption, dynamic, FieldDto>(
captions,
x => new { x.FieldName, x.Context, x.SourceTable },
y => new { y.FieldName, y.Context?.Name, y.SourceTable },
(field, captions) =>
{
Caption caption = captions.FirstOrDefault();
return caption == null ? field : field.With(y => y.FieldName = caption.DisplayName ?? y.FieldName);
})
This is the current production code, which achieves the same thing:
return fields.Select(x =>
{
Caption caption = captions.FirstOrDefault(captionFilter.FilterByAll(x.FieldName, x.Context, x.SourceTable));
return caption == null ? x : x.With(y => y.FieldName = caption.DisplayName ?? y.FieldName);
});
This could be simplified by the utility method. In the end, it would look something like this:
return fields
.LeftJoin(captions, (field, caption) => captionFilter.FilterByAll(field.FieldName, field.Context, field.SourceTable))
.Select((field,caption) => field.With(y => y.FieldName = caption.DisplayName ?? y.FieldName));
Items without a match should proceed as usual so we can skip the null reference check.