【问题标题】:Error System.Collections.Generic.List`1[System.String] when itry String.Join on a list of result在结果列表上尝试 String.Join 时出错 System.Collections.Generic.List`1[System.String]
【发布时间】:2021-01-22 21:45:39
【问题描述】:

当我尝试在结果列表中使用 String.Join 时,我收到错误 System.Collections.Generic.List`1[System.String]。

例如,我有两个这样的列表:

var list1= new List<string>{"string1","string2"};
var list2= new List<string>{"string1"};

然后我想收到一条消息,其中包含未出现在 list2 上的字符串

var resultList1 = list1.Except(list2).ToList(); // this line get a list with "string2"

当我使用 String.Join 时,我收到错误 System.Collections.Generic.List`1[System.String]。我也尝试了 resultList1.Cast() 而不是 resultList1 具有相同的结果。

var message = "List strings not found:\n\n"
                + String.Join(",", $"\n\n{resultList1}\n\n");

【问题讨论】:

  • 我不确定错误 message 到底是什么,但我最好的猜测是string.Join() 的第二个参数需要是一个集合。
  • 请收下tour,阅读How to Ask,学习使用formatting

标签: c# list


【解决方案1】:

你需要像ths这样使用字符串连接,

var message = "List strings not found:\n\n" + String.Join(",", resultList1);

您在可枚举数组上使用系统连接,但是当您使用 $"\n\n{result1}\n\n" 字符串插值时,您基本上是在连接一个不起作用的单个字符串。

String.Join 接受一个字符串(逗号、换行符或任何字符串),它结合了数组中的所有元素,但是当你给出字符串而不是数组或集合时,它会报错。

最后,Documentation 应该有助于深入解释有关用法的更多信息。

【讨论】:

  • 谢谢你的回答。对我很有帮助
  • @Andres 如果帖子回答了您的问题,请务必点击投票数下方的 ✔ 将其标记为已回答
猜你喜欢
  • 2018-03-09
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2019-05-13
相关资源
最近更新 更多