【问题标题】:C# list add works but not append? [duplicate]C#列表添加有效但不能追加? [复制]
【发布时间】:2020-07-16 05:37:37
【问题描述】:

我正在使用 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

【问题讨论】:

  • 在线搜索 "c# SomeMethodName" 通常会将您带到文档中,找到无法按您期望的方式工作的方法。在那里您可以阅读有关如何使用它的信息。

标签: c# list append


【解决方案1】:

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

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

一般来说,我会坚持使用List&lt;string&gt;.Add(string),除非您实际处理的是IEnumerable&lt;T&gt; 对象。

【讨论】:

  • 有没有办法添加到开头或者我必须在列表中添加一个空元素,然后移动所有内容并将我的新元素放在末尾?非常感谢你的帮助顺便说一句
  • 您可以使用List&lt;T&gt;.Insert() 方法在列表中的任意位置插入。要在开头插入,请使用索引0,例如:x.Insert(0, "greetings");
  • @mizuprogrammer 还有一个随附的Prepend 方法,它将项目添加到可枚举的开头。
猜你喜欢
  • 1970-01-01
  • 2021-06-11
  • 2020-09-24
  • 2021-01-10
  • 2020-08-04
  • 2016-01-22
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
相关资源
最近更新 更多