问题描述
如果我有一个项目列表,并且说"id"是唯一的,但不一定是顺序的,是否有办法找到列表或IEnumerable中的上一个实体?
If I have a list of items, and say the "id" is unique, but not necessarily sequential, is there a way to find the previous entity in say either a List or an IEnumerable?
因此,我可能有一个人员列表,他们每个人都有一个ID,并且按照我不知道的顺序对其进行排序.我得到的只是这个人的名单和身份证.
So I may have a list of people, and they each have an id and they are sorted in an order I am not aware of. All I get is the list and the id of the person.
现在我需要让前一个人进入提供给我的ID.
Now I need to get the previous person to the id that was provided to me.
是否有一种不错的LINQ方式来做到这一点?或者我只是找到记录并在ForEach中获得前一个记录?
Is there a nice LINQ way to do this or do I simply find the record and get the previous one in a ForEach?
修改我才发现这是最好的方法吗?
editI just found this, is this the best approach?
推荐答案
我认为您需要这个
items.TakeWhile(x => x.id != id).LastOrDefault();
-
Enumerable.TakeWhile
方法只要指定条件为true,就会从序列中返回元素,然后跳过其余元素. - 我们从中取出最后一个或
default
. Enumerable.TakeWhile
Method returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.- We take the last or
default
from it.
这篇关于使用LINQ将先前的记录获取到当前记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!