gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:26:12 25 4
gpt4 key购买 nike

我发布这个更多的是作为一个学习练习,而不是因为我需要将实现从命令式循环中移除。我的问题是如何将此循环转换为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com