c# - 将字符串列表转换为字节数组

标签 c# arrays list encoding

我正在尝试编写一个接受 List<string> 的方法然后将整个列表转换为一个大字节数组。像这样:

private byte[] ConvertStringsToBytes(List<string> list)
{
    List<byte> byteList = new List<byte>();

    foreach (var i in list)
    {
        byteList.Add(Encoding.UTF8.GetBytes(i));
    }

    return byteList.ToArray();
}

但是我得到:

Argument type 'byte[]' is not assignable to paramter type 'byte' on the byteList.Add(Encoding.UTF8.GetBytes(i));

我哪里错了?如何正确地将此列表转换为一个字节数组?

最佳答案

一种更有效的方法是首先将字符串连接在一起,然后将其转换为字节数组,如下所示:

List<string> input = new List<string> { "first", "second" };
string fullString = String.Join(String.Empty, list.ToArray());
byte[] byteArray = Encoding.UTF8.GetBytes(fullString);

如果性能很重要并且您在该列表中有很多字符串,您会喜欢这样: 编辑:经过基准测试,这种方法确实比上面的慢。

List<string> input = new List<string> { "first", "second" };
StringBuilder sb = new StringBuilder();
foreach (string s in input )
    sb.Append(s);

byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());

编辑: 对这篇文章中提到的一些方法进行了一些基准测试。这是发布版本的输出:

ConvertWithString         896ms
ConvertWithStringBuilder  858ms
ConvertWithConcat        1529ms
ConvertWithSelectMany    2234ms
ConvertWithBuffer         904ms

ConvertWithString         501ms
ConvertWithStringBuilder  919ms
ConvertWithConcat        1435ms
ConvertWithSelectMany    2044ms
ConvertWithBuffer         636ms

如果您没有很多字符串,看起来性能并不重要。

代码如下:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    internal class Program
    {
        static byte[] ConvertWithBuffer(List<string> list)
        {
            int totalSize = list.Sum(x => Encoding.UTF8.GetByteCount(x));
            byte[] buffer = new byte[totalSize];

            int ix = 0;

            foreach (string str in list)
                ix += Encoding.UTF8.GetBytes(str, 0, str.Length, buffer, ix);

            return buffer;
        }

        static byte[] ConvertWithConcat(List<string> list) { return Encoding.UTF8.GetBytes(String.Concat(list)); }

        static byte[] ConvertWithSelectMany(List<string> list)
        {
            return list
                .SelectMany(line => Encoding.UTF8.GetBytes(line))
                .ToArray();
        }

        static byte[] ConvertWithString(List<string> input)
        {
            string fullString = String.Join(String.Empty, input.ToArray());
            return Encoding.UTF8.GetBytes(fullString);
        }

        static byte[] ConvertWithStringBuilder(List<string> input)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in input)
                sb.Append(s);

            return Encoding.UTF8.GetBytes(sb.ToString());
        }

        static IEnumerable<string> CreateList()
        {
            for (int i = 0; i < 10000000; i++)
                yield return i.ToString();
        }

        static void Main(string[] args)
        {
            List<string> strings = CreateList().ToList();
            Stopwatch stopWatch = Stopwatch.StartNew();

            // warm up
            ConvertWithString(strings);
            ConvertWithStringBuilder(strings);
            ConvertWithConcat(strings);
            ConvertWithSelectMany(strings);
            ConvertWithBuffer(strings);

            // testing

            stopWatch.Restart();
            ConvertWithString(strings);
            Console.WriteLine("ConvertWithString {0}ms", stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            ConvertWithStringBuilder(strings);
            Console.WriteLine("ConvertWithStringBuilder {0}ms", stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            ConvertWithConcat(strings);
            Console.WriteLine("ConvertWithConcat {0}ms", stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            ConvertWithSelectMany(strings);
            Console.WriteLine("ConvertWithSelectMany {0}ms", stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();
            ConvertWithBuffer(strings);
            Console.WriteLine("ConvertWithBuffer {0}ms", stopWatch.ElapsedMilliseconds);

            Console.WriteLine("press any key...");
            Console.ReadKey();
        }
    }
}

关于c# - 将字符串列表转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31982063/

相关文章:

c# - 使用 foreach 循环遍历列表(或数组)作为对序列

python list(zipobject) 返回空(列表)容器

python - 就地修改列表 : Calculating a sieve of primes in a python list

arrays - 如何在 Coldfusion 中附加 <cfloop> 中的数组值?

c# - 如何通过id删除列表中的多个对象?

c# - 在换行面板中设置最大行数

c# - 订阅者方法不需要创建委托(delegate)实例?

c# - 具有泛型的 FileHelpers 主/详细记录

c# - 拳击,已成为过去?

c - 将二维数组传递给 c 中的函数