Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq get first or last element when List index out-of-range

Tags:

c#

list

linq

With a List of articles, when one article is displayed I also display the next and previous article, I use the code below. I'm looking for a way to make this code leaner with 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;
like image 502
David Lenn Avatar asked Dec 06 '25 07:12

David Lenn


1 Answers

I don't think LINQ offers an "next or first" operation. Might as well use modulo:

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

(The + allArticles.Count in the second line is to correct for the mathematically wrong behavior of % when it is applied to negative numbers.)

like image 162
Aasmund Eldhuset Avatar answered Dec 08 '25 21:12

Aasmund Eldhuset