使用Linq在集合中指定元素之后查找元素 [英] Using Linq to find the element after a specified element in a collection

查看:225
本文介绍了使用Linq在集合中指定元素之后查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份人的有序列表.我有一个我认识的人存在于该收藏集中.如何确定列表中的下一个是谁?

解决方案

您可以执行以下操作:

IEnumerable<Person> persons = ..

var firstPersonAfterJack = persons.SkipWhile(p => p.Name != "Jack")
                                  .ElementAt(1); //Zero-indexed, means second

这个想法是产生一个序列,该序列会导致元素跳过直到满足条件为止,然后获取该序列中的第二个元素.

如果不能保证查询将返回结果(例如,从未找到匹配项,或者该序列的最后一个元素),则可以将ElementAt替换为ElementAtOrDefault,然后执行null测试以检查成功/失败.

我注意到您在问题中说,您有一个订购的名单.如果您可以更详细地解释这意味着什么,我们也许可以提供更好的答案(例如,我们可能不必线性搜索序列).

I have an ordered list of People. I have a person that I know exists in that collection. How can I determine which person is next in the list?

解决方案

You could do something like this:

IEnumerable<Person> persons = ..

var firstPersonAfterJack = persons.SkipWhile(p => p.Name != "Jack")
                                  .ElementAt(1); //Zero-indexed, means second

The idea is to produce a sequence resulting in skipping elements until you meet the condition, then take the second element of that sequence.

If there's no guarantee that the query will return a result (e.g. a match is never found, or is the last element of the sequence), you could replace ElementAt with ElementAtOrDefault, and then do a null-test to check for success / failure.

I notice you say in your question that you have an ordered list of people. If you could explain what that means in more detail, we might be able to provide a better answer (for example, we may not have to linear-search the sequence).

这篇关于使用Linq在集合中指定元素之后查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆