当列表索引超出范围时,Linq获取第一个或最后一个元素

本文关键字:获取 Linq 第一个 元素 最后一个 索引 列表 范围 | 更新日期: 2023-09-27 18:13:29

对于文章列表,当显示一篇文章时,我也会显示下一篇和上一篇文章,我使用下面的代码。我正在寻找一种方法,使这个代码与Linq精简?

var article = allArticles.Where(x => x.UrlSlug == slug).FirstOrDefault();
int currentIndex = allArticles.IndexOf(article);
        if (currentIndex + 1 > allArticles.Count-1)
            article.Next = allArticles.ElementAt(0);
        else
            article.Next = allArticles.ElementAt(currentIndex + 1);
        if (currentIndex - 1 >= 0)
            article.Previous = allArticles.ElementAt(currentIndex - 1);
        else
            article.Previous = allArticles.Last();
return article;

当列表索引超出范围时,Linq获取第一个或最后一个元素

我不认为LINQ提供"下一个或第一个"操作。不妨使用modulo:

article.Next = allArticles[(currentIndex + 1) % allArticles.Count];
article.Previous = allArticles[(currentIndex + allArticles.Count - 1) % allArticles.Count];

(第二行中的+ allArticles.Count是为了纠正%在应用于负数时的数学错误行为)

完全同意Aasmund Eldhuset的回答。

确保你没有得到一个null异常:

var article = allArticles.FirstOrDefault(x => x.UrlSlug == slug);
var currentIndex = allArticles.IndexOf(article);
if (article == null) return;
article.Next = allArticles[(currentIndex + 1) % allArticles.Count];
article.Previous = allArticles[(currentIndex + allArticles.Count - 1) % allArticles.Count];