public class CarDTO
{
public int CarId { get; set; }
public string CarName { get; set; }
public List<PolicySummaryDTO> PolicySummaries { get; set; }
}
public class PolicySummaryDTO
{
public long PolicyId { get; set; }
public string PolicyName { get; set; }
public decimal Amount { get; set; }
}
I have List<CarDTO> Cars
each car has already list of policies List<PolicySummaryDTO> PolicySummaries
.
PolicyId
is filled. But other properties like PolicyName
, Amount
, etc. are not.
The thing I need to do is get data from DB _contex.PolicySummary
and I need to complete missing fields.
I know that I could do this in this way.
Get all PolicyIds
var policyIds = cars.SelectMany(t => t.PolicySummaries).Select(r => r.PolicyId);
Get PolicyData based on Ids
var policyData = _context.PolicySummary.Where(t => policyIds.Contains(t.PolicyId));
And then using foreach I can fill data.
foreach (var car in cars) { foreach (var policy in car.PolicySummaries) { var policyDataToUse = policyData.Single(t => t.PolicyId == policy.PolicyId); policy.Amount = policyDataToUse.Amount; policy.PolicyName = policyDataToUse.PolicyName; } }
Everthing will works fine, but I wondering whether I can do it in more elegant way, maybe using somehow LINQ JOIN
or something, or maybe my solution is totally correct?
EDIT - solution with dictionary
var policyIds = cars.SelectMany(t => t.PolicySummaries).Select(r => r.PolicyId);
var policyDict = _context.PolicySummary.Where(t => policyIds.Contains(t.PolicyId)).ToDictionary(t => t.PolicyId);
foreach (var car in cars)
{
foreach (var policy in car.PolicySummaries)
{
var policyDataToUse = policyDict[policy.PolicyId];
policy.Amount = policyDataToUse.Amount;
policy.PolicyName = policyDataToUse.PolicyName;
}
}