如何在多个条件下使用SkipWhile
本文关键字:SkipWhile 条件下 | 更新日期: 2023-09-27 18:08:09
我试图用SkipWhile
过滤对象,但它不评估多个条件。
下面是演示问题的示例代码,
int[] numbers = { 1, 2, 3, 4, 5 };
var result = numbers.SkipWhile(n => n < 2 && n != 2).ToList();
当第一个条件为true
时,该查询选择2,3,4,5
,省略第二个条件(n != 2
)。
是否有可能使查询对两个条件都求值?
编辑:我的实际情况类似于
... dateRanges
.OrderBy(d=>d.Sequence)
.SkipWhile(d => d.FromDate <= currentDate && d.ToDate >= currentDate)
.Skip(1).First();
在DateTime文件上操作,以选择列表中的下一个对象
编辑2:
我已经创建了一个示例程序,它类似于我的实际代码保存数据的类
public class DateRange
{
public int Sequence { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
}
项目static void Main(string[] args)
{
var dateRanges = new List<DateRange>(){
new DateRange{Sequence = 1 , FromDate = new DateTime(2014,1,1), ToDate = new DateTime(2014,1,31)},
new DateRange{Sequence = 2 , FromDate = new DateTime(2014,2,1), ToDate = new DateTime(2014,2,28)},
new DateRange{Sequence = 3 , FromDate = new DateTime(2014,3,1), ToDate = new DateTime(2014,3,31)},
new DateRange{Sequence = 4 , FromDate = new DateTime(2014,4,1), ToDate = new DateTime(2014,4,30)},
new DateRange{Sequence = 5 , FromDate = new DateTime(2014,5,1), ToDate = new DateTime(2014,5,31)},
};
var myDate = new DateTime(2014, 2, 10); // A Date in Fabruary
//This query selects {2, 2014/2/1, 2014/2/28}
var selectedItem = dateRanges.OrderBy(d => d.Sequence)
.Where(d => d.FromDate <= myDate && d.ToDate >= myDate)
.First();
//What I actually need to select is {3, 2014/3/1, 2014/3/31}
//Which is next item of the list
//This is what i have tried
//But this query also selects {2, 2014/2/1, 2014/2/28}
var nextItem = dateRanges.OrderBy(d => d.Sequence)
.SkipWhile(d => d.FromDate <= myDate && d.ToDate >= myDate)
.Skip(1).First();
//Because, results of this part of query returns objects from {1, 2014/1/1, 2014/1/31} ...
var unexpectdItems = dateRanges.OrderBy(d => d.Sequence)
.SkipWhile(d => d.FromDate <= myDate && d.ToDate >= myDate);
}
它是对两个条件求值——但是只要条件是false
,就返回序列的其余部分。一旦n==2
, n < 2 && n != 2
就是false
。事实上,你的条件没有任何意义——如果n
小于2,那么不可能等于2。
基本上不清楚你想要实现什么,但你使用的条件是不合适的-如果你想检查每个值的条件,而不仅仅是"值直到条件不满足",那么你应该使用Where
而不是SkipWhile.
SkipWhile(d => d.FromDate <= myDate && d.ToDate >= myDate)
现在看数据的第一项:
new DateRange{Sequence = 1 , FromDate = new DateTime(2014,1,1),
ToDate = new DateTime(2014,1,31)},
And myDate
:
var myDate = new DateTime(2014, 2, 10);
数据的第一项是否满足条件?不,因为ToDate
(1月31日)不大于或等于myDate
(2月10日)。所以SkipWhile
不会跳过任何项目。也许你想要||
而不是&&
?