2010-08-20 79 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() }; 
相關問題