Most efficient way to append arrays in C#?

前端 未结 10 2092
挽巷
挽巷 2020-12-02 19:39

I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don\'t initially know the final number of samples I will actually retrieve.

What i

相关标签:
10条回答
  • 2020-12-02 20:19

    Concatenating arrays is simple using linq extensions which come standard with .Net 4

    Biggest thing to remember is that linq works with IEnumerable<T> objects, so in order to get an array back as your result then you must use the .ToArray() method at the end

    Example of concatenating two byte arrays:

    byte[] firstArray = {2,45,79,33};
    byte[] secondArray = {55,4,7,81};
    byte[] result = firstArray.Concat(secondArray).ToArray();
    
    0 讨论(0)
  • 2020-12-02 20:23

    I believe if you have 2 arrays of the same type that you want to combine into a third array, there's a very simple way to do that.

    here's the code:

    String[] theHTMLFiles = Directory.GetFiles(basePath, "*.html");
    String[] thexmlFiles = Directory.GetFiles(basePath, "*.xml");
    List<String> finalList = new List<String>(theHTMLFiles.Concat<string>(thexmlFiles));
    String[] finalArray = finalList.ToArray();
    
    0 讨论(0)
  • 2020-12-02 20:26

    using this we can add two array with out any loop.

    I believe if you have 2 arrays of the same type that you want to combine into one of array, there's a very simple way to do that.

    Here's the code:

    String[] TextFils = Directory.GetFiles(basePath, "*.txt");
    String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
    String[] finalArray = TextFils.Concat(ExcelFils).ToArray();
    

    or

    String[] Fils = Directory.GetFiles(basePath, "*.txt");
    String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
    Fils = Fils.Concat(ExcelFils).ToArray();
    
    0 讨论(0)
  • 2020-12-02 20:28

    I recommend the answer found here: How do I concatenate two arrays in C#?

    e.g.

    var z = new int[x.Length + y.Length];
    x.CopyTo(z, 0);
    y.CopyTo(z, x.Length);
    
    0 讨论(0)
提交回复
热议问题