Note that there are some explanatory texts on larger screens.

plurals
  1. POSelecting "custom distinct" items from a List using LINQ
    text
    copied!<p>I have a generic List of Policy objects.</p> <p>The list contains the following data</p> <pre><code>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 </code></pre> <p>I want to select the one row containing the highest policySequence for each policyNumber, so that I end up with the following:</p> <pre><code>id policyNumber policySequence created 3 101 3 cccc 4 102 1 dddd 6 103 2 ffff </code></pre> <p>I have a solution below using a foreach, but was wondering if there was an easier, cleaner way to do this in LINQ?</p> <pre><code>class Program { static void Main(string[] args) { List&lt;Policy&gt; policyList = new List&lt;Policy&gt; { 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&lt;Policy&gt; filteredPolicyList = new List&lt;Policy&gt;(); foreach(var policy in policyList) { if(!filteredPolicyList.Exists(x =&gt; x.policyNumber == policy.policyNumber)) { filteredPolicyList.Add(policy); } else { var currentPolicyInFilteredList = filteredPolicyList.Where(x =&gt; x.policyNumber == policy.policyNumber).First(); if (policy.policySequence &gt; currentPolicyInFilteredList.policySequence) { filteredPolicyList.Remove(currentPolicyInFilteredList); filteredPolicyList.Add(policy); } } } } } public class Policy { public int id; public int policyNumber; public int policySequence; public string otherData; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload