David Lenn
David Lenn

Reputation: 175

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

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;

Upvotes: 2

Views: 1026

Answers (2)

Imran Rizvi
Imran Rizvi

Reputation: 7438

Totally agree with Aasmund Eldhuset answer.

Just make sure you don't get a null exception:

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];

Upvotes: 1

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

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.)

Upvotes: 8

Related Questions