1 minute read

I had a table on SQL 2005 I am accessing it via LINQ. I had to select an item via a “where” condition (see below).

var item = (from snap in adc.Snapshots
      where snap.file == image
      select snap).First();

<p>The problem was that I needed to identify the previous item and the next item too because we had to show them on a web page. Talking with some collgues of mine we found the following way that looks quite smart:</p> <p>var previous = adc.Snapshots.OrderByDescending(s => s.InsertDateTime).Where(s => string.Compare(s.file, image) < 0).FirstOrDefault();
var item = adc.Snapshots.OrderBy(s => s.InsertDateTime).Where(s => s.file == image).SingleOrDefault();
var next = adc.Snapshots.OrderBy(s => s.InsertDateTime).Where(s => string.Compare(s.file, image) > 0).FirstOrDefault();
</p>