当List索引超出范围时,Linq获取第一个或最后一个元素

Dav*_*enn 2 c# linq list

使用文章列表,当显示一篇文章时,我还会显示下一篇和上一篇文章,我使用下面的代码.我正在寻找一种方法来使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)

Aas*_*set 8

我不认为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第二行中的内容是为了纠正将数字%应用于负数时的数学错误行为.)

  • @LInsoDeTeh:`Where()`可以工作,但这基本上要求你指定索引必须等于我上面使用的表达式,然后你需要调用`First()`来减少产生的`IEnumerable`到一个实际的元素 - 所以它将是一种更复杂的方式来实现相同的元素查找.(你不需要`Select()`,因为没有元素的转换.) (2认同)