tags:

views:

456

answers:

4

If i have an object of type Photo and a Result set which is sorted in a particular order, is there a way for me to get the position of the current Photo object in the result set. and then get all objects that would follow it?

A: 

Not sure if I understand correctly but this might help:

var result = photos.Skip(100); // 100 would be the position of current object.

// if you don't know the index of the current object:
// This won't work on LINQ to SQL directly, do it on a list or something.
var result = photos.SkipWhile(x => x != currentObject).Skip(1);

In reality, if you are dealing with a database, there should be some identifier (a set of columns) you are sorting by. If you want to do the whole thing on the server side, you can grab the properties of the current object and filter the result set specifically for objects that would come after that in the sort order you want.

Mehrdad Afshari
How do i get the position of the current object though.
maxfridbe
A: 

Index of the photo:

result.IndexOf(photo);

Items after it:

result.SkipWhile((q, i) => i <= result.IndexOf(photo));
Yuriy Faktorovich
I'm assuming that result is already sorted by him, and not the order coming from the database.
Yuriy Faktorovich
+1  A: 

If you're sorting against an Id:

// gets the previous photo, or null if none:
var previousPhoto = db.Photos
    .Where(p => p.Id < currentPhotoId)
    .OrderByDescending(p => p.Id)
    .FirstOrDefault();

// gets the next photo, or null if none:
var nextPhoto = db.Photos
    .Where(p => p.Id > currentPhotoId)
    .OrderBy(p => p.Id)
    .FirstOrDefault();

If you have custom ordering, you'd need to replace the OrderBy/OrderByDescending expression with your custom ordering. You'd also need to use the same ordering criteria in Where() to get only those photos before or after the current photo.

Ben M
+2  A: 

You can do something like this (not terribly efficient):

var result =
  photos.Select((p, i) => new { Index = i, Photo = p })
  .SkipWhile(x => x.Photo != photo).Skip(1);

This will give you all photos following photo combined with their index in the original collection.

Martin Liversage
SkipWhile includes an indexed overload.
Yuriy Faktorovich
Yes, but that overload is only useful if you want to use the index to determine what to skip. I want to keep the original index across both the `SkipWhile` and the `Skip`.
Martin Liversage