c# - 从列表创建滑动窗口

标签 c# linq

我需要在获取下一个和上一个项目时遍历列表。我目前是这样做的:

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/

相关文章:

当 lambda 表达式没有时,Linq to CRM(早期绑定(bind))join 语句会引发异常

c# - 序列包含多个元素

c# - 按月将值放入数据表组

c# - 如果字符串值不为 null 或为空,则在字符串中添加 "| "

c# - 在哪里可以找到默认的 wpf 图表模板?

C# 创建具有动态属性的对象 : LINQ select List<object> values by property names array

c# - 根据标准比较两个对象

c# - WebClient DownloadString() 计数器?

c# - 使用 cmd.exe 执行 DEL 命令的代码需要很长时间

c# - Visual Studio 注册表捕获实用程序已停止工作,在 Windows7 中编译 C# 项目时出错