IEnumerable:在与谓词匹配的最后一个字符之前获取所有字符 [英] IEnumerable: Get all before the last that matches a predicate

查看:47
本文介绍了IEnumerable:在与谓词匹配的最后一个字符之前获取所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的IEnumerable<int>,只是更长的时间:

I have an IEnumerable<int> like this, only longer:

5, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 6, 0, 0, 0, 0, 0

现在我想返回最后一个非零值之前的所有元素:

and now I want to return all elements before the last non-zero value:

5, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0

sequence.Last()似乎无济于事,因为它返回的是最后一次出现的索引,而不是最后一次出现的索引.

It seems sequence.Last() doesn't help here, because it returns the last occurrence, not the index of the last occurrence.

我曾考虑使用

var lastIndex = sequence.LastIndex(x=>x!=0);
subsequence = sequence.Take(lastIndex);

在通常情况下可以使用,但LastIndex不存在,或者

which would work in the general case, but LastIndex doesn't exist, or

var last = sequence.Last(y=>y!=0);
subsequence = sequence.TakeWhile(x=>x!=last)

在示例中有效,但在通常情况下(可能存在重复的非零值)无效.

which would work on the example, but not in the general case, where there may be duplicated non-zero values.

有什么想法吗?

推荐答案

您可以尝试

var allDataBeforeLastNonZero= sequence.GetRange(0,sequence.FindLastIndex(x=>x!=0));

这篇关于IEnumerable:在与谓词匹配的最后一个字符之前获取所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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