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;
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With