查找集合中的下一个记录:LINQ [英] Find next record in a set: LINQ
问题描述
我有一个所有具有id属性的对象列表
I have a list of objects which all have an id property
例如
1、10、25、30、4
1, 10, 25, 30, 4
我有一个currentId,我需要在列表中找到下一个ID
I have a currentId and I need to find the next Id in the list
因此,例如,当前ID设置为25,我需要返回ID为30的对象.此后的对象为4.
So for example current Id is set to 25, I need to return the object with an id of 30. The one after that would be 4.
我将如何在LINQ中优雅地做到这一点?
How would I do this elegantly in LINQ?
编辑
该列表由"sort"属性排序.因此,您不能只按ID排序,因为那样会使订单搞乱.
The list is ordered by a "sort" property. So you cannot just order by id, as that would mess up the order.
推荐答案
无需重新排序(请注意,由于我认为我读错了问题,我进行了少许编辑):
Without re-ordering (note I edit slightly as I think I misread the question):
int[] data = {1, 10, 25, 30, 4};
int last = 25;
var next = data.SkipWhile(i => i != last).Skip(1).First();
很明显,如果data
是一组对象,则类似于:
Obviously, if data
was a set of objects, something like:
var next = data.SkipWhile(obj => obj.Id != last).Skip(1).First();
这篇关于查找集合中的下一个记录:LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!