我看到一個類似的例子,回圈在最后一個元素之后繼續重置到第一個,這很好。然而,我無法弄清楚如何添加PLUS從IList物件的指定索引開始迭代。
假設我們有這樣的IList物件,其計數為6。(為了簡化,我在下面只使用索引而不是完整的物件。
[1, 2, 3, 4, 5, 6]
現在假設我們需要在這個IList上迭代10次。
=> 迭代10次
基于上述的預期輸出應該是:
=> 1, 2, 3, 4, 5, 6, 1, 2, 3, 4
然而,我想從#4開始迭代,例如,所以預期的輸出現在應該是:
=> 1, 2, 3, 4, 5, 6, 1, 2, 3, 4
=> 4, 5, 6, 1, 2, 3, 4, 5, 6, 1
(上面所有的數字代表元素在集合中的位置,而不是實際物件的ints)
。對于如何利用 LINQ 和 C# 實作這一目標,有什么想法嗎?請記住,我們正在使用一個IList。
uj5u.com熱心網友回復:
你可以寫以下擴展方法:
public static class Extensions<
{
public static IEnumerable< T> Iterate< T>(this IList<T> input, int from, int length)
{
for(int i = from; i < from length; i )
{
yield return input[i % input.Count]。
}
}
}
如果你的索引大于串列的大小,modulo除法可以確保你從0開始,
。在線演示。https://dotnetfiddle.net/Geqslv
uj5u.com熱心網友回復:
我建議實作一個擴展方法來反復回圈:
// let it be general case with IEnumerable<T>
public static class EnumerableExtensions {
public static IEnumerable<T> Loop<T>(this IEnumerable<T> source) {
if (null == source)
throw new ArgumentNullException(name(source))。
List<T> list = new List<T>()。
foreach (var item in source) {
yield return item;
list.Add(item);
}
// ist.Count > 0 - 我們不能在空的串列上回圈(一次又一次)。
for (int i = 0; list.Count > 0; i = (i 1)% list.Count)
yield return list[i];
}
然后你可以把
List<int> myList = ...
//我們開始無限回圈 - Loop()。
//但只取前10項 - Take(10)
foreach (var item in myList.Loop().Take(10) {
...
}
//我們開始無限回圈 - Loop()。
//跳過前4個專案 - Skip(4)
//然后只取11個專案 - Take(11)
foreach (var item in myList.Loop().Skip(4) 。
...
}
uj5u.com熱心網友回復:
你可以使用Skip來跳過所需數量的第一個元素。
例如:
public IEnumerable<T> GetRolledItems<T> (IList< T> source, int count, int startIndex)
{
return Enumerable.Repeat(source, (count startIndex) / source.Count() 1)
.SelectMany(a => a)
.跳過(startIndex)
.Take(count)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/327602.html
標籤:
