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

C# Linq在列表索引超出范围时获取第一个或最后一个元素,c#,linq,list,C#,Linq,List,对于文章列表,当显示一篇文章时,我还显示下一篇和上一篇文章,我使用下面的代码。我正在寻找一种方法,通过Linq使代码更精简 var article = allArticles.Where(x => x.UrlSlug == slug).FirstOrDefault(); int currentIndex = allArticles.IndexOf(article); if (currentIndex + 1 > allArticles.Count-1)

对于文章列表,当显示一篇文章时,我还显示下一篇和上一篇文章,我使用下面的代码。我正在寻找一种方法,通过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提供了“下一个或第一个”操作。不妨使用模:

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

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

完全同意Aasmund Eldhuset的回答

只需确保不会出现空异常:

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];
LINQ没有“next”或“first”操作,它对
Where
和包含索引的
Select
子句有重载。因此,使用
.Where((content,index)=>)
Select((content,index)=>)
可以用LINQ实现。@linodeth:
Where()
可以工作,但这基本上需要您指定索引必须等于我上面使用的表达式,然后您需要首先调用
将生成的
IEnumerable
减少为实际元素-因此这将是实现相同元素查找的更复杂的方法。(您不需要
Select()
,因为元素没有转换。)