How do I select the top of the list as long as the items at the top of the list have a property with a specific value.
I need the Linq statement to see that there is a break in the sequence and the only return the top two items. The problem is that I don’t know exactly how many items are going to have the correct property value.
I have been working through this problem with LinqPad 4. The code below is a copy and past from LinqPad 4. The results, “q”, should not contain SomeData with an EffectiveDate of 4/5/2011 because the Kind property on hsc2 is “KindTwo”.
I am trying to find the value most resent value of “Kind” and then only take the top records that match that value until I get to a record that doesn’t match that value.
void Main()
{
var hsc1 = new SomeData {EffectiveDate = new DateTime(2011,4,5), Kind = "KindOne"};
var hsc2 = new SomeData {EffectiveDate = new DateTime(2011,4,10), Kind = "KindTwo"};
var hsc3 = new SomeData {EffectiveDate = new DateTime(2011,4,20), Kind = "KindOne"};
var hsc4 = new SomeData {EffectiveDate = new DateTime(2011,4,25), Kind = "KindOne"};
var all = new [] {hsc1, hsc2, hsc3, hsc4};
var lastSomeData = all.OrderByDescending((x) => x.EffectiveDate).First();
lastSomeData.Dump();
var q = from h in all
where h.Kind == lastSomeData.Kind
orderby h.EffectiveDate descending
select h;
q.Dump();
}
// Define other methods and classes here
class SomeData
{
public DateTime EffectiveDate {get;set;}
public string Kind {get;set;}
}
This is a fully working Console Application that does what you asked. As I was not the first to propose the use of TakeWhile in this question, please do not mark my answer as the accepted one.