使用文章列表,当显示一篇文章时,我还会显示下一篇和上一篇文章,我使用下面的代码.我正在寻找一种方法来使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;
Run Code Online (Sandbox Code Playgroud)
我不认为LINQ提供"下一个或第一个"操作.不妨使用模数:
article.Next = allArticles[(currentIndex + 1) % allArticles.Count];
article.Previous = allArticles[(currentIndex + allArticles.Count - 1) % allArticles.Count];
Run Code Online (Sandbox Code Playgroud)
(+ allArticles.Count第二行中的内容是为了纠正将数字%应用于负数时的数学错误行为.)
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |