2010-08-20 92 views
3

我有一个通用的策略对象列表。使用LINQ从列表中选择“自定义不同”项目

列表包含以下数据

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<Policy> policyList = new List<Policy> 
              { 
               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<Policy> filteredPolicyList = new List<Policy>(); 

      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; 
    } 

回答

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

一个注记那些发现这个问题的人。如果要由组多个条件http://stackoverflow.com/questions/5231845/c-sharp-linq-group-by-on-multiple-columns .GroupBy(p值=>新 { p.criteria , p.criteria1, p.criteria2, }) – DFTR 2013-10-03 19:29:01

2

如果您使用LINQ到对象,你可以使用MoreLINQ项目DistinctBy方法:

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

你可以组和汇总:

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