简体   繁体   English

从其他一维 arrays 初始化一维数组

[英]Initializing a one-dimensional array from other one-dimensional arrays

I feel like this has a really simple answer and I just can't get to it, but here's my shot on it after not finding anything related on the internet.我觉得这有一个非常简单的答案,我就是无法理解,但这是我在互联网上找不到任何相关内容后的拍摄。
Esentially, I would like to do something like this from javascript in C#:基本上,我想从 C# 中的 javascript 做这样的事情:

var abc = ["a", "b", "c"]
var abcd = [...abc, "d"]

"Spreading" the content of the one-dimensional array abc into another one-dimensional array abcd , adding new values during initialization.将一维数组abc的内容“传播”到另一个一维数组abcd中,在初始化期间添加新值。
Replicating this behaviour in C#, however, won't work as intended:但是,在 C# 中复制此行为将无法按预期工作:

string[] abc = { "a", "b", "c" };
string[] abcd = { abc, "d" };

The closest I got to replicating this in C# was with Lists, like so:我在 C# 中最接近复制它的是列表,如下所示:

string[] abc = { "a", "b", "c" };
var abcd = new List<string>();
abcd.AddRange(abc);
abcd.Add("d");

I could've saved a line in the above example by directly initializing the List with the "d" string (the order doesn't matter to me, I'll just be checking if the collection contains a certain item I'm looking for), but using a List is in itself highly inefficient in comparison to initializing an array since I have no intention on modifying or adding items later on.我可以通过直接用“d”字符串初始化列表来在上面的示例中保存一行(顺序对我来说并不重要,我只是检查集合是否包含我正在寻找的某个项目),但与初始化数组相比,使用 List 本身效率非常低,因为我无意稍后修改或添加项目。
Is there any way I can initialize a one-dimensional array from other one-dimensional arrays in one line?有什么方法可以在一行中从其他一维 arrays 初始化一维数组?

If you're looking for a one-liner, you may use the Enumerable.Append() method .如果您正在寻找单线,您可以使用Enumerable.Append()方法 You may add a .ToArray() at the end if want the type of abcd to be a string array.如果希望abcd的类型为字符串数组,您可以在末尾添加一个.ToArray()

There you go:你有 go:

string[] abcd = abc.Append("d").ToArray();

Note: The Append() method is available in .NET Framework 4.7.1 and later versions注意: Append()方法在 .NET Framework 4.7.1 及更高版本中可用

For .NET Framework 4.7 or older, one way would be to use the Enumerable.Concat() method :对于 .NET 框架 4.7 或更早版本,一种方法是使用Enumerable.Concat()方法

string[] abcd = abc.Concat(new[] { "d" }).ToArray();
string[] abcde = abc.Concat(new[] { "d", "e" }).ToArray();

In 1 line:在 1 行中:

string[] abc = { "a", "b", "c" };
var abcd = new List<string>(abc) { "d" };

The constructor of a list can take another list.列表的构造函数可以采用另一个列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM