如果我有如下集合:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
是否可以按正常顺序迭代这些元素,但从特定元素开始?我不想遗漏任何一个,而且这个收藏保持不变很重要。但对于中间步骤,我需要按以下顺序收集与这些元素相关的信息:0、15、14(也就是按递减顺序迭代,从0开始,然后按该顺序返回到15和14)?
也许前臂循环对我来说不起作用,但我正在努力确定一种最有效的方法。
澄清:
对于任何类型为List<int>
的int集合,其中保证我有从0到某个数字的整数,我希望以递增或递减的顺序迭代这些项,指定一个起始元素,并使迭代环绕以确保所有元素都只迭代一次。
到目前为止我学到了什么:
我真的很感激我已经得到的所有帮助。我想我发现,开发另一个包含我想要的元素和顺序的系列对于我想做的事情是必要的。到目前为止,我会不断评估每个人的建议,并随时向每个人发布。
对我有效的方法:
请参阅我标记为最有用的答案,以及我在这里提出的通过制作类似的静态方法来扩展的答案,该方法在需要时提供了我在递增方向上寻找的内容:
public static IEnumerable<T> GetRangeIncreasing<T>(IList<T> source, int startPosition, int count)
{
var index = startPosition;
for (int counter = 0; counter < count; counter++)
{
yield return source[index];
index = (index + 1)%source.Count;
if (index > source.Count - 1)
index -= source.Count;
}
}
看起来反向迭代器才是您真正想要的。最简单的方法是使用IList<T>
,因为它支持索引访问。
public static IEnumerable<T> GetRangeDecreasing<T>(IList<T> source, int startPosition, int count)
{
var index = startPosition;
for (int counter = 0; counter < count; counter++)
{
yield return source[index];
index = (index - 1) % source.Count;
if (index < 0)
index += source.Count;
}
}
使用
IList<int> input = Enumerable.Range(0, 16).ToArray();
var output = GetRangeDecreasing(input, 0, 3);
output
将包含3个元素:0
、15
和14
。
集合将需要支持索引器,以便您可以对其执行item[i]
并获得所需的元素。如果可能的话,只需使用一个倒计时的for
循环,但首先获取0的特殊情况。
static IEnumerable<int> GetInSpecialOrder(YourCollectionType items)
{
if(items.Length > 0)
yield return items[0];
for (int i = items.Length - 1; i > 0; i--)
yield return items[i];
}
您可以颠倒集合的顺序,并将0索引项添加到顶部。
请参见反向:http://msdn.microsoft.com/en-us/library/bb358497.aspx
假设任何索引集合:
// array for simplicity
int[] myArr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
// get indexes 0, 14, 15
var myInts = myArr.Where((n, i) => i == 0 || i => 14)
.ToArray();
对数组进行重新排序就像将值从一个索引插入另一个索引一样简单。这似乎是一个非常特殊的要求;但是,此示例显示了如何通过索引器本身使用LINQ来选择数组(索引)值。