我正在尝试使用SkipWhile
过滤对象,但它不会评估多个条件。
以下是演示此问题的示例代码,
int[] numbers = { 1, 2, 3, 4, 5 };
var result = numbers.SkipWhile(n => n < 2 && n != 2).ToList();
此查询选择2,3,4,5
,当第一个条件为n != 2
时,会忽略第二个条件(true
)。
是否可以让查询评估这两个条件?
修改
我的实际情况类似于
... 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);
}
答案 0 :(得分:6)
评估两个条件 - 但只要条件为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)},
myDate
:
var myDate = new DateTime(2014, 2, 10);
您的病情是否满足您的第一项数据?不,因为ToDate
(1月31日)不大于或等于myDate
(2月10日)。因此SkipWhile
不会跳过任何项目。也许您想要||
而不是&&
? (目前还不清楚这个查询的目的是什么。)