LINQ-SkipWhile损坏了吗? [英] LINQ - is SkipWhile broken?

查看:66
本文介绍了LINQ-SkipWhile损坏了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶地发现以下代码的结果,我只想从整数序列中删除所有3:

I'm a bit surprised to find the results of the following code, where I simply want to remove all 3s from a sequence of ints:

var sequence = new [] { 1, 1, 2, 3 };
var result = sequence.SkipWhile(i => i == 3); // Oh noes! Returns { 1, 1, 2, 3 }

为什么不跳过3个?

我的下一个想法是,好的,Except运算符可以解决问题:

My next thought was, OK, the Except operator will do the trick:

var sequence = new [] { 1, 1, 2, 3 };
var result = sequence.Except(i => i == 3); // Oh noes! Returns { 1, 2 }

总之,

  • 除了删除3,还要 删除不明显的元素. .
  • SkipWhile不跳过最后一个 元素,即使它与 健康)状况.嗯.
  • Except removes the 3, but also removes non-distinct elements. Grr.
  • SkipWhile doesn't skip the last element, even if it matches the condition. Grr.

有人可以解释为什么SkipWhile不跳过最后一个元素吗?有人能建议我使用什么LINQ运算符从上面的序列中删除"3"吗?

Can someone explain why SkipWhile doesn't skip the last element? And can anyone suggest what LINQ operator I can use to remove the '3' from the sequence above?

推荐答案

它没有损坏. SkipWhile将仅跳过IEnumerable<T>开头的项目.一旦不满足该条件,它将很乐意使用其余元素.以后不会与之匹配的其他元素.

It's not broken. SkipWhile will only skip items in the beginning of the IEnumerable<T>. Once that condition isn't met it will happily take the rest of the elements. Other elements that later match it down the road won't be skipped.

int[] sequence = { 3, 3, 1, 1, 2, 3 };
var result = sequence.SkipWhile(i => i == 3); 
// Result: 1, 1, 2, 3

这篇关于LINQ-SkipWhile损坏了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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