我需要在获取下一个和上一个项目时遍历列表。我目前是这样做的:
var items = collection.ToList();
for (int index = 0; index < items.Count; index++)
{
var prevItem = index == 0 ? null : items[index - 1];
var currentItem = items[index];
var nextItem = (index + 1) == items.Count ? null : items[index + 1];
// do work
}
这项工作但它不如我想要的那么好和可读。是否有更易读的方式来创建滑动窗口?这不涉及所有丑陋的三元检查。我觉得有一个更友好的方式使用 select, skip, take, and default if empty
最佳答案
恕我直言,如果您希望它可重用,则最好使用生成器解决此类问题。
public static IEnumerable<(T PrevItem, T CurrentItem, T NextItem)>
SlidingWindow<T>(this IEnumerable<T> source, T emptyValue = default)
{
using (var iter = source.GetEnumerator())
{
if (!iter.MoveNext())
yield break;
var prevItem = emptyValue;
var currentItem = iter.Current;
while (iter.MoveNext())
{
var nextItem = iter.Current;
yield return (prevItem, currentItem, nextItem);
prevItem = currentItem;
currentItem = nextItem;
}
yield return (prevItem, currentItem, emptyValue);
}
}
然后使用它:
foreach (var (prevItem, currentItem, nextItem) in collection.SlidingWindow())
{
// do stuff with prevItem, currentItem, nextItem
}
关于c# - 从列表创建滑动窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054872/