C# 使用 LINQ 合并 2 个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16012380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:42:21  来源:igfitidea点击:

Merge 2 arrays using LINQ

c#linqdata-structures

提问by

I have two simple array and I would like to merge using join linq:

我有两个简单的数组,我想使用 join linq 进行合并:

int[] num1 = new int[] { 1, 55, 89, 43, 67, -3 };
int[] num2 = new int[] { 11, 35, 79, 23, 7, -10 };

var result = from n1 in num1
             from n2 in num2
             select result;

回答by dasblinkenlight

You can do it using Concatand ToArray, like this:

您可以使用Concatand 来完成ToArray,如下所示:

var res = num1.Concat(num2).ToArray();

This will put all elements of num2after elements of num1, producing resthat looks like

这将把所有元素的num2后元素num1,产生res看起来像

int[] { 1, 55, 89, 43, 67, -3, 11, 35, 79, 23, 7, -10 };

EDIT :(in response to a comment: "how can I also sort either allNumbers and res?")

编辑:(回应评论:“我如何才能对 allNumbers 和 res 进行排序?”)

Once your two arrays are merged, you can use OrderByto sort the result, like this:

合并两个数组后,您可以使用OrderBy对结果进行排序,如下所示:

var res = num1.Concat(num2).OrderBy(v=>v).ToArray();

回答by Chris Dixon

var allNumbers = num1.Concat(num2);

回答by MuhammadHani

Use Concat

Concat

  var res= num1.Concat(num2);

回答by Binary Worrier

var result = num1.Concat(num2);

Doesn't allocate any memory. Is this sufficient for your needs?

不分配任何内存。这是否足以满足您的需求?

回答by Pandian

try like below... it will help you..

尝试像下面...它会帮助你...

int[] num1 = new int[] { 1, 55, 89, 43, 67, -3 };
int[] num2 = new int[] { 11, 35, 79, 23, 7, -10 };
var result = num1.Union(num2).ToArray();