如果我有一个Photo类型的对象和一个按特定顺序排序的结果集,有没有办法让我获得当前Photo对象在结果集中的位置。然后获取它后面的所有对象?
发布于 2009-08-13 00:12:35
如果您正在对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();如果您有自定义排序,则需要将OrderBy/OrderByDescending表达式替换为自定义排序。您还需要在Where()中使用相同的排序标准,以便仅获取当前照片之前或之后的那些照片。
发布于 2009-08-13 00:31:38
你可以这样做(效率不是很高):
var result =
photos.Select((p, i) => new { Index = i, Photo = p })
.SkipWhile(x => x.Photo != photo).Skip(1);这将为您提供所有遵循photo的照片,以及它们在原始集合中的索引。
发布于 2009-08-13 00:01:25
不确定我是否理解正确,但这可能会有所帮助:
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);实际上,如果您正在处理一个数据库,那么应该有一些标识符(一组列)作为排序依据。如果你想在服务器端做所有的事情,你可以抓取当前对象的属性,并按照你想要的排序顺序过滤结果集。
https://stackoverflow.com/questions/1269355
复制相似问题