如何根据C#中的某些条件从列表中获取下一个项目?

时间:2015-11-10 19:12:19

标签: c# linq

我有一个List,其中包含一组时间范围(DataTime format)。它有StartDateTime& EndDateTime。我试图根据条件获得列表的下一项。我怎么能这样做?

例如,

foreach (var currentTimeSlot in prepBlock.EligiblePickupTimes.BlockList)
{
    if (potentialStartTime > currentTimeSlot.EndDateTime)
    {
        //Skip current time slot and grab next one and so on.
    }
}

enter image description here

3 个答案:

答案 0 :(得分:1)

您可以使用FirstOrDefault来获取与谓词匹配的第一项:

prepBlock.EligiblePickupTimes.BlockList
    .FirstOrDefault(x => potentialStartTime <= x.EndDateTime);

您可以使用Enumerable<T>从第一个匹配条件中获取整个SkipWhile个项目到最后:

prepBlock.EligiblePickupTimes.BlockList
    .SkipWhile(x => potentialStartTime > x.EndDateTime);

第一个条件等同于以下代码:

prepBlock.EligiblePickupTimes.BlockList
    .SkipWhile(x => potentialStartTime > x.EndDateTime)
    .FirstOrDefault();

根据您在图片中看到的内容,您可以执行以下操作:

returnValue.IsEstimateSuccessful &= !prepBlock.EligiblePickupTimes.BlockList
    .SkipWhile(x => potentialStartTime > x.EndDateTime)
    .Any();

答案 1 :(得分:0)

除非我遗漏了某些内容,否则我相信您可以使用评论中提到的.FirstOrDefault方法完成此操作。

using System.Linq;
...

var nextAvailableItem =
    prepBlock.EligiblePickupTimes.BlockList
    // reversing your condition above to find value I want
    // instead of specifying values I don't want
    .FirstOrDefault(x => potentialStartTime <= x.EndDateTime)
    ;

// did we find a value to match our condition?
var wasFound = nextAvailableItem != default(DateTime);

答案 2 :(得分:0)

如果您只是想尝试遍历其中potentialStartTime大于EndDateTime的所有时间段,那么:

foreach (var currentTimeSlot in
  prepBlock.EligiblePickupTimes.BlockList.Where(x=>potentialStartTime > x.EndDateTime))
{
}

根据您的图片,我认为这正是您所寻找的:

returnValue.IsEstimateSuccessful=!prepBlock
  .EligiblePickupTimes
  .BlockList
  .Any(x=>potentialStartTime > x.EndDateTime);

如果在此之前设置了returnValue.IsEstimateSuccessful(就像你将其默认为true,并且许多检查可能将其设置为false):

returnValue.IsEstimateSuccessful&=!prepBlock
  .EligiblePickupTimes
  .BlockList
  .Any(x=>potentialStartTime > x.EndDateTime);