Merge 2 arrays using LINQ

前端 未结 5 482
孤城傲影
孤城傲影 2021-01-04 00:59

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

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


        
相关标签:
5条回答
  • 2021-01-04 01:16

    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();
    
    0 讨论(0)
  • 2021-01-04 01:24
    var result = num1.Concat(num2);
    

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

    0 讨论(0)
  • 2021-01-04 01:27

    You can do it using Concat and ToArray, like this:

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

    This will put all elements of num2 after elements of num1, producing res that looks like

    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?")

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

    var res = num1.Concat(num2).OrderBy(v=>v).ToArray();
    
    0 讨论(0)
  • 2021-01-04 01:30
    var allNumbers = num1.Concat(num2);
    
    0 讨论(0)
  • 2021-01-04 01:36

    Use Concat

      var res= num1.Concat(num2);
    
    0 讨论(0)
提交回复
热议问题