我有一个包含整数的数组Y,例如[1 3 2 0 9 8 2],我想选择除了第一个和最后一个元素之外的所有元素 [3, 2, 0, 9, 8, 2],以便在后续操作中使用它们。
这是我目前的方法:
Y.Where((i, x) => i != 0 && i != Y.Length - 1)
有更好的方法来做这件事吗?
我有一个包含整数的数组Y,例如[1 3 2 0 9 8 2],我想选择除了第一个和最后一个元素之外的所有元素 [3, 2, 0, 9, 8, 2],以便在后续操作中使用它们。
这是我目前的方法:
Y.Where((i, x) => i != 0 && i != Y.Length - 1)
既然您已经知道长度,您可以使用 Skip
和 Take
,就像这样:
var res = Y.Skip(1).Take(Y.Length-2);
Y.Length
是否至少为2。如果你只想限制自己在已知长度的集合中使用,那么dasblinkenlight的方法可能是最好的选择。如果不知道长度,可以添加以下扩展方法(未经测试):
public static IEnumerable<T> SkipEnd<T>(this IEnumerable<T> source,
int countToSkip)
{
// TODO: Validation
T[] buffer = new T[countToSkip];
int index = 0;
bool returning = false;
foreach (var item in source)
{
if (returning)
{
yield return buffer[index];
}
buffer[index] = item;
index++;
if (index == countToSkip)
{
index = 0;
returning = true;
}
}
}
然后你可以使用:
var elements = original.Skip(1).SkipEnd(1);
Queue<T>
。例如:public static IEnumerable<T> SkipEnd<T>(this IEnumerable<T> source,
int countToSkip)
{
// TODO: Validation
Queue<T> queue = new Queue<T>(countToSkip);
foreach (var item in source)
{
if (queue.Count == countToSkip)
{
yield return queue.Dequeue();
}
queue.Enqueue(item);
}
}