C#Linq Lambda for group by multiple columns选择max

时间:2018-03-21 16:16:58

标签: 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();

2 个答案:

答案 0 :(得分:1)

我认为没有办法在一条线上做到这一点。所以我的尝试是:

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();

答案 1 :(得分:0)

_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()