检索列表中的上一个索引记录(如果存在)

时间:2019-01-26 16:13:06

标签: c#

我正在使用.NET 3.5。我的要求是遍历按日期降序排列的对象列表,找到特定记录的匹配项,捕获该对象,然后,如果在该日期之前的日期存在一条记录,这意味着捕获的对象的索引减去一个(如果存在),也捕获该对象,这意味着我的输出列表可以有一个记录或两个记录,具体取决于是否有以前的日期记录。有没有一种干净的方法可以做到这一点?

我尝试捕获匹配记录的索引,并通过向索引加-1来获取先前的索引>>如果前一个元素不存在,则存在索引超出范围的风险。

如何避免索引超出范围异常,而又检查是否存在前一个元素(如果存在)?我敢肯定,有一种比我尝试的方法更清洁的方法。因此,如果有更好的方法,我会向您提出建议。

任何建议都受到高度赞赏。谢谢

2 个答案:

答案 0 :(得分:0)

看看下面的内容。对象只是datetimeoffset,但应说明LINQ查询。您正在寻找.Top(2)(如果您需要按某些内容将其分组,则可能会更加复杂):

下面的LinqPad示例,但应轻松粘贴到控制台应用中。

void Main()
{
    var threeItems = new List<DateTimeOffset>(new[] { DateTimeOffset.Now, DateTimeOffset.Now.AddDays(-1), DateTimeOffset.Now.AddDays(-2) });
    var twoItems = new List<DateTimeOffset>(new[] { DateTimeOffset.Now, DateTimeOffset.Now.AddDays(-1) });
    var oneItem = new List<DateTimeOffset>(new[] { DateTimeOffset.Now });

    ShowItems(GetItems(threeItems));
    ShowItems(GetItems(twoItems));
    ShowItems(GetItems(oneItem));
}

IEnumerable<DateTimeOffset> GetItems(List<DateTimeOffset> items)
{
    return items
        .OrderByDescending(i => i)
        .Select(i => i)
        .Take(2);
}

void ShowItems(IEnumerable<DateTimeOffset> items)
{
    Console.WriteLine("List of Items:");

    foreach (var item in items)
    {
        Console.WriteLine(item);
    }
}

答案 1 :(得分:0)

我认为您要查找的内容将需要使用List.IndexOf来找到匹配项的索引,如果在搜索日期之前有日期时间,则检索上一个项目。这里的示例使用一个名为listObject的对象,该对象包含日期时间以及其他属性;

        DateTime searchDate = DateTime.Parse("26/01/2019");

        var orderedList = listObjects.OrderBy(x => x.DateProperty).ToList();
        listObject matchingItem = orderedList.First(x => x.DateProperty.Date == searchDate.Date);   //gets the first matching date
        listObject previousMatching = orderedList.Any(x => x.DateProperty.Date < searchDate.Date) ? orderedList[orderedList.IndexOf(matchingItem) - 1] : null;  //returns previous if existing, else returns null