I need select all elements from a set whose Id property is contained within a second set. Can “SelectMany()” be used to accomplish this? What is the most efficient / best solution for this type of matching problem.
Example:
Select all DateRangeIds for a given ReportId by way of a joining entity set.
Sets:
- Reports {ReportId, ReportName}
- ReportDateRanges {DateRangeId, ReportId, ReportDateRangeId}
- DateRanges {DateRangeId, DateRangeName}
Here is my solution’s code. I am unsure if this is the proper approach, but this does solve the problem I’ve described:
var report = Reports.Take(1).FirstOrDefault();
int reportId = Convert.ToInt32(report.Id);
var dateRangeIds = ReportDateRanges.Where(rdr => rdr.ReportId == reportId).OrderBy(it => it.DateRangeId).Select(it => it.DateRangeId);
var dateRanges = DateRanges.Where(dateRange => dateRangeIds.Contains(dateRange.Id));
LINQ experts, please feel free to critique this code and offer any suggestions. Thanks for the help!
Well, you can use an Enumerable.Intersect(Of TSource) Method (IEnumerable(Of TSource), IEnumerable(Of TSource), IEqualityComparer(Of TSource))
for example:
result
Using overload specified in link, you can specify
EqualityComparerfor your custom object in order to find intersection of both enumerations.Hope this helps.