C# 列表添加有效但不追加?

标签 c# list append

这个问题在这里已经有了答案:





Difference between a List's Add and Append method?

(2 个回答)


去年关闭。




我正在使用 C# System.Collections.Generic List 并且 Add 函数按预期工作但 Append 什么也不做?为什么是这样?我觉得我遗漏了一些明显的东西,但我看不到什么,我使用它与 Add 一样,但它不起作用?

List<string> x = new List<string>();
x.Add("hello");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Add("hi");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Append("oi");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Append("aye");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();

输出:
hello

hello
hi

hello
hi

hello
hi

最佳答案

Append返回更新后的集合,而不是修改原始集合。

正确的用法类似于 var y = x.Append("foo") .请注意,您不能存储 Append 的结果。回到 x ,因为它返回类型为 IEnumerable<string> 的引用而不是 List<string> .

一般来说,我会坚持使用 List<string>.Add(string) , 除非您实际上是在处理 IEnumerable<T>目的。

关于C# 列表添加有效但不追加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61022245/

相关文章:

ruby - 如何将 Ruby 中的 puts 文本保存到 txt 文件中?

c# - 不指定参数和返回类型的函数指针

c# - 单击 winform 应用程序中的按钮后,如何将焦点返回到上次使用的控件?

r - 如何将 nlsList 中的系数获取到数据框中?

python - 创建不是同一个列表的空白列表的字典

javascript - 如何转义jQuery的append函数中的空格和连字符?

c# - EF Core2.2 : Scaffold-DbContext not working with named connection string in WPF project

c# - 谁负责缓存/内存功能结果?

R:如何连接向量列表中的字符串向量

list - 如何在 Prolog 中 append 列表?