C# 如何将新元素添加到现有的二维字符串数组中?
如何在c#中向二维字符串数组添加新元素? 我有一个数组C# 如何将新元素添加到现有的二维字符串数组中?,c#,C#,如何在c#中向二维字符串数组添加新元素? 我有一个数组 string [,] x = new string[,]{{"1","a"},{"2","b"}}; 现在我想增加长度数组,并在顶部添加“3”和“c”。数组的长度是不变的。一旦定义,对象就不能添加到其中 您需要一个可扩展的集合,如自定义类的列表 public class FooBar { public string Foo { get; set; } public string Bar { get; set; } }
string [,] x = new string[,]{{"1","a"},{"2","b"}};
现在我想增加长度数组,并在顶部添加“3”和“c”。数组的长度是不变的。一旦定义,对象就不能添加到其中 您需要一个可扩展的集合,如自定义类的
列表
public class FooBar
{
public string Foo { get; set; }
public string Bar { get; set; }
}
和列表一样
var fooBars = new List<FooBar>
{
new FooBar() {Foo = "1", Bar = "a"},
new FooBar() {Foo = "2", Bar = "b"},
};
fooBars.Add(new FooBar() {Foo = "3", Bar = "c"});
不能在C#中调整数组的大小。 但有两种解决方案适合您:
列表
https://msdn.microsoft.com/en-gb/library/6sh2ey19(v=vs.110).aspx
var x = new List<List<string>>();
x.Add(new List<string>()
{
"1", "a"
});
// so on.
字典
(unic第一个字段,称为Key)。
https://msdn.microsoft.com/en-gb/library/xfhwa508(v=vs.110).aspx
var x = new List<List<string>>();
x.Add(new List<string>()
{
"1", "a"
});
// so on.
var x=新列表();
x、 添加(新列表()
{
“1”、“a”
});
//等等。
无法调整.NET数组的大小。创建一个新的、更大的数组,或者使用列表
。我建议您尽可能多地使用列表。@RoJa尽可能多,就像在内存关闭之前一样。