使用LINQ从List中选择“custom distinct”项

我有一个通用的Policy对象列表。

该列表包含以下数据

id policyNumber policySequence otherData 1 101 1 aaaa 2 101 2 bbbb 3 101 3 cccc 4 102 1 dddd 5 103 1 eeee 6 103 2 ffff 

我想为每个policyNumber选择包含最高policySequence的一行,以便我最终得到以下结果:

 id policyNumber policySequence created 3 101 3 cccc 4 102 1 dddd 6 103 2 ffff 

我在下面使用foreach有一个解决方案,但是想知道在LINQ中是否有更简单,更清晰的方法来执行此操作?

 class Program { static void Main(string[] args) { List policyList = new List { new Policy {id = 1, policyNumber = 101, policySequence = 1, otherData = "aaaa"}, new Policy {id = 2, policyNumber = 101, policySequence = 2, otherData = "bbbb"}, new Policy {id = 3, policyNumber = 101, policySequence = 3, otherData = "cccc"}, new Policy {id = 4, policyNumber = 102, policySequence = 1, otherData = "dddd"}, new Policy {id = 5, policyNumber = 103, policySequence = 1, otherData = "eeee"}, new Policy {id = 6, policyNumber = 103, policySequence = 2, otherData = "ffff"} }; List filteredPolicyList = new List(); foreach(var policy in policyList) { if(!filteredPolicyList.Exists(x => x.policyNumber == policy.policyNumber)) { filteredPolicyList.Add(policy); } else { var currentPolicyInFilteredList = filteredPolicyList.Where(x => x.policyNumber == policy.policyNumber).First(); if (policy.policySequence > currentPolicyInFilteredList.policySequence) { filteredPolicyList.Remove(currentPolicyInFilteredList); filteredPolicyList.Add(policy); } } } } } public class Policy { public int id; public int policyNumber; public int policySequence; public string otherData; } 

 var maxPolicies = policyList .GroupBy(p => p.PolicyNumber) .Select(grp => grp.OrderByDescending(p => p.PolicySequence).First()); 

如果你正在使用LINQ to Objects,你可以使用MoreLINQ项目的DistinctBy方法:

 var maxPolicies = policyList.OrderByDescending(x => x.PolicySequence) .DistinctBy(x => x.PolicyNumber); 

您可以分组和汇总:

 var result = from p in policyList group p by p.policyNumber into g select new { Policy = g.Key, Max = g.Max() };