mqp*_*mqp 180
return list.Where((x, i) => i % nStep == 0);
Run Code Online (Sandbox Code Playgroud)
Mic*_*odd 37
我知道这是"老派",但为什么不使用带有步进= n的for循环?
Mar*_*ner 33
听起来好像
IEnumerator<T> GetNth<T>(List<T> list, int n) {
for (int i=0; i<list.Count; i+=n)
yield return list[i]
}
Run Code Online (Sandbox Code Playgroud)
会做的伎俩.我没有看到使用Linq或lambda表达式的必要性.
编辑:
做了
public static class MyListExtensions {
public static IEnumerable<T> GetNth<T>(this List<T> list, int n) {
for (int i=0; i<list.Count; i+=n)
yield return list[i];
}
}
Run Code Online (Sandbox Code Playgroud)
你用LINQish的方式写作
from var element in MyList.GetNth(10) select element;
Run Code Online (Sandbox Code Playgroud)
第二编辑:
为了使它更加LINQish
from var i in Range(0, ((myList.Length-1)/n)+1) select list[n*i];
Run Code Online (Sandbox Code Playgroud)
Jar*_*Par 25
您可以使用Where过载将索引与元素一起传递
var everyFourth = list.Where((x,i) => i % 4 == 0);
Run Code Online (Sandbox Code Playgroud)
Qui*_*son 10
对于循环
for(int i = 0; i < list.Count; i += n)
//Nth Item..
Run Code Online (Sandbox Code Playgroud)
小智 6
我认为如果您提供 linq 扩展,您应该能够在最不特定的接口上进行操作,从而在 IEnumerable 上进行操作。当然,如果您追求速度,特别是对于大 N,您可能会为索引访问提供重载。后者消除了迭代大量不需要的数据的需要,并且比Where子句快得多。提供两个重载可以让编译器选择最合适的变体。
public static class LinqExtensions
{
public static IEnumerable<T> GetNth<T>(this IEnumerable<T> list, int n)
{
if (n < 0)
throw new ArgumentOutOfRangeException("n");
if (n > 0)
{
int c = 0;
foreach (var e in list)
{
if (c % n == 0)
yield return e;
c++;
}
}
}
public static IEnumerable<T> GetNth<T>(this IList<T> list, int n)
{
if (n < 0)
throw new ArgumentOutOfRangeException("n");
if (n > 0)
for (int c = 0; c < list.Count; c += n)
yield return list[c];
}
}
Run Code Online (Sandbox Code Playgroud)