gpt4 book ai didi

c# - IEnumerable 流

转载 作者:可可西里 更新时间:2023-11-01 08:27:27 25 4
gpt4 key购买 nike

我想做一些与下面的代码示例大致相同的事情。我想生成并提供数据流,而不必在任何时候将整个数据集都存储在内存中。

似乎我需要一些接受 IEnumerable<string> 的 Stream 实现(或 IEnumerable<byte> )在其构造函数中。在内部,此 Stream 只会在读取 Stream 或需要时遍历 IEnumerable。但我不知道有这样的 Stream 实现。

我走在正确的轨道上吗?你知道有什么方法可以做这样的事情吗?

    public FileStreamResult GetResult()
{
IEnumerable<string> data = GetDataForStream();

Stream dataStream = ToStringStream(Encoding.UTF8, data);

return File(dataStream, "text/plain", "Result");
}

private IEnumerable<string> GetDataForStream()
{
StringBuilder sb;
for (int i = 0; i < 10000; i++)
{
yield return i.ToString();
yield return "\r\n";
}
}

private Stream ToStringStream(Encoding encoding, IEnumerable<string> data)
{
// I have to write my own implementation of stream?
throw new NotImplementedException();
}

最佳答案

这是一个只读的 Stream使用 IEnumerable<byte> 的实现作为输入:

public class ByteStream : Stream, IDisposable
{
private readonly IEnumerator<byte> _input;
private bool _disposed;

public ByteStream(IEnumerable<byte> input)
{
_input = input.GetEnumerator();
}

public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => 0;
public override long Position { get; set; } = 0;

public override int Read(byte[] buffer, int offset, int count)
{
int i = 0;
for (; i < count && _input.MoveNext(); i++)
buffer[i + offset] = _input.Current;
return i;
}

public override long Seek(long offset, SeekOrigin origin) => throw new InvalidOperationException();
public override void SetLength(long value) => throw new InvalidOperationException();
public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException();
public override void Flush() => throw new InvalidOperationException();

void IDisposable.Dispose()
{
if (_disposed)
return;
_input.Dispose();
_disposed= true;
}
}

然后您仍然需要一个函数来转换 IEnumerable<string>IEnumerable<byte> :

public static IEnumerable<byte> Encode(IEnumerable<string> input, Encoding encoding)
{
byte[] newLine = encoding.GetBytes(Environment.NewLine);
foreach (string line in input)
{
byte[] bytes = encoding.GetBytes(line);
foreach (byte b in bytes)
yield return b;
foreach (byte b in newLine)
yield return b;
}
}

最后,这里是如何在你的 Controller 中使用它:

public FileResult GetResult()
{
IEnumerable<string> data = GetDataForStream();
var stream = new ByteStream(Encode(data, Encoding.UTF8));
return File(stream, "text/plain", "Result.txt");
}

关于c# - IEnumerable 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22047900/

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