C# Linq Lambda 用于按多列分组,选择最大值



我想将其转换为lambda语法,但似乎无法使其工作:

按两列分组,在另一列上选择 max,返回完整复杂对象的列表。

我在这里写了更多的文字来通过这个表格的验证。 在允许我发布此内容之前需要多少文本?

_clientpolicies = (from policy in
    _reply.CommercialInsuredGroupWithPolicyTerm.InsuredWithPolicyTerm.SelectMany(x => x.PolicyTerm)
        .Where(x => !(string.IsNullOrWhiteSpace(x.PolicyNumber) && string.IsNullOrWhiteSpace(x.ControlNumber)))
        .Where(x => x.Insured.DNBAccountNumber == _client.LookupID)
          group policy by
          new
          {
              PolicyReference = GetPolicyReference(policy),
              PolicyType = policy.ProductInformation.PolicyTypeCode
          }
          into g
          let maxPolicyInception = g.Max(p => p.InceptionDate)
          from policyGroup in g
          where policyGroup.InceptionDate == maxPolicyInception
          select policyGroup).ToList();
我认为

没有办法在一行中做到这一点。所以我的尝试:

policyGroups= 
     _reply.CommercialInsuredGroupWithPolicyTerm.InsuredWithPolicyTerm
                .SelectMany(x => x.PolicyTerm)
                .Where(x => !(string.IsNullOrWhiteSpace(x.PolicyNumber) && string.IsNullOrWhiteSpace(x.ControlNumber)))
                .Where(x => x.Insured.DNBAccountNumber == _client.LookupID)
                .GroupBy(x => GetPolicyReference(x))
                .ThenBy(x => x.ProductInformation.PolicyTypeCode)
                .ToList();
var maxPolicyInception = policyGroups.Max(p => p.InceptionDate);
_clientpolicies = policyGroups
                 .Where(g => g.InceptionDate == maxPolicyInception)
                 .ToList();
_clientpolicies =
                _reply.CommercialInsuredGroupWithPolicyTerm.InsuredWithPolicyTerm.SelectMany(x => x.PolicyTerm)
                    .Where(x => !(string.IsNullOrWhiteSpace(x.PolicyNumber) && string.IsNullOrWhiteSpace(x.ControlNumber)))
                    .Where(x => x.Insured.DNBAccountNumber == _client.LookupID)
                    .GroupBy(x => 
                        new
                        {
                            PolicyReference = GetPolicyReference(x),
                            PolicyType = x.ProductInformation.PolicyTypeCode
                        },
                        (key, g) => g.OrderByDescending(gx => gx.InceptionDate).First()

最新更新