Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linq列表到字节数组_Linq_Csv_Asp.net Core - Fatal编程技术网

Linq列表到字节数组

Linq列表到字节数组,linq,csv,asp.net-core,Linq,Csv,Asp.net Core,我在谷歌搜索,但没有得到简单的答案。有没有办法将linq列表转换为字节数组 public FileResult GetCustomerListCSV() { List<Customer> CustomerList = new List<Customer>(); CustomerList = dbContext.Customer.ToList(); // Need to convert this into byte array return File(Custo

我在谷歌搜索,但没有得到简单的答案。有没有办法将linq列表转换为字节数组

public FileResult GetCustomerListCSV()
{
  List<Customer> CustomerList = new List<Customer>();
  CustomerList = dbContext.Customer.ToList(); // Need to convert this into byte array
  return File(CustomerList, "text/csv", "CustomerList.csv");
}
公共文件结果GetCustomerListCSV() { List CustomerList=新列表(); CustomerList=dbContext.Customer.ToList();//需要将其转换为字节数组 返回文件(CustomerList,“text/csv”,“CustomerList.csv”); }
请提供帮助。

您必须先创建CSV字符串,然后将其转换为字节:

var lines = CustomerList.Select(c => $"{c.Id}, {c.Name}");
var csv = string.Join(Environment.NewLine, lines);
var bytes = Encoding.UTF8.GetBytes(csv);
return File(bytes, "text/csv", "CustomerList.csv");
或者,使用库:


这看起来有点奇怪。你能解释一下你想如何处理在字节数组中转换的客户列表吗?我想作为csv文件下载。最好使用在内存或磁盘中为你创建csv文件的特定库。Net core将自动创建csv,但我需要将linq列表转换为字节数组
using var ms = new MemoryStream();
using var writer = new StreamWriter(ms);
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
        
csv.WriteRecords(CustomerList);
csv.Flush();
ms.Seek(0, SeekOrigin.Begin);

return File(ms, "text/csv", "CustomerList.csv");