c# - 如何从 IEnumerable 中剥离 block ?

标签 c# linq

我发布这个更多的是作为一个学习练习,而不是因为我需要将实现从命令式循环中移除。我的问题是如何将此循环转换为 LINQ?给定一个字节的输入 IEnumerable,它被认为是 8 字节的“ block ”。输出 IEnumerable 应该删除任何包含 0 的 block 。

粗略的命令式实现

    private static IEnumerable<byte> StripBlocksWithZeroes(IEnumerable<byte> input)
    {
        var stripped = new List<byte>();
        var inputArray = input.ToArray();
        for (int i = 0; i < inputArray.Length; i += 8)
        {
            if (inputArray[i + 0] != 0 &&
                inputArray[i + 1] != 0 &&
                inputArray[i + 2] != 0 &&
                inputArray[i + 3] != 0 &&
                inputArray[i + 4] != 0 &&
                inputArray[i + 5] != 0 &&
                inputArray[i + 6] != 0 &&
                inputArray[i + 7] != 0)
            {
                stripped.Add(inputArray[i + 0]);
                stripped.Add(inputArray[i + 1]);
                stripped.Add(inputArray[i + 2]);
                stripped.Add(inputArray[i + 3]);
                stripped.Add(inputArray[i + 4]);
                stripped.Add(inputArray[i + 5]);
                stripped.Add(inputArray[i + 6]);
                stripped.Add(inputArray[i + 7]);
            }
        }
        return stripped;
    }

最佳答案

在我的脑海中:

inputArray.Select((item, index) => new {item, groupIndex = index / 8})
          .GroupBy(x => x.groupIndex)
          .Where(g => g.All(x => x.item != 0))
          //.Select(g => g.First().item)
          .SelectMany(g => g.Select(x => x.item))

一些解释:

使用 groupIndex 标记每个项目,利用整数除法,因此每个连续的 8 组将具有相同的 groupIndex。

按组索引分组,所以现在我们有一个序列序列。

对于每个内部序列,确保它不包含零。

将生成的序列序列展平为单个序列。

关于c# - 如何从 IEnumerable 中剥离 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24814681/

相关文章:

c# - 将日期时间列转换为 SQL Server 中的 datetime2 列?

c# - 如何在Sand CaSTLe/MAML的代码示例中为类名称着色

c# - 如何使用 LINQ 从数据库中选择多个项目

C# 自定义 Linq 提供程序

c# - 使用 LINQ 将值一分为二

c# - 将执行以下哪些 linq 查询

c# - Linq 方法正文最佳实践问题

c# - 什么时候应该使用 C# Generic Func<T,Tresult>?

c# - 如何用方法语法编写查询

C# 和 WPF - 'System.Reflection.TargetInvocationException' 发生在PresentationFramework.dll 中