代码之家  ›  专栏  ›  技术社区  ›  niki b

传递数组,然后使用OrderBy vs Sort-更改原始数组[重复]

  •  0
  • niki b  · 技术社区  · 7 年前

    为什么 ArrayCalledWithOrderBy ArrayCalledWithSort

    编辑:对于建议重复的链接。一个链接中甚至没有OrderBy,因此它显然不是重复的。另一个链接实际上是询问OrderBy和Sort之间哪个选项更好,而不是为什么不更改原始数组。

    public static void ArrayCaller()
    {
       var arr = new string[] { "pink", "blue", "red", "black", "aqua" };
       DisplayArray(arr, "Before method calls");
    
       ArrayCalledWithOrderBy(arr);
       DisplayArray(arr, "After method call using orderby");
    
       ArrayCalledWithSort(arr);
       DisplayArray(arr, "After method call using sort");
    }
    
    public static void ArrayCalledWithOrderBy(string[] arr)
    {
        // this does not change the original array in the calling method. Why not?
        arr = (arr.OrderBy(i => i).ToArray()); 
        DisplayArray(arr, "After orderby inside method");
    }
    
    public static void ArrayCalledWithSort(string[] arr)
    {
        // this changes the original array in the calling method. 
        // Because it is using the same reference? 
        // So the above code for orderby does not?
        Array.Sort(arr);
        DisplayArray(arr, "After sort inside method");
    }
    
    public static void DisplayArray(string[] arr, string msg)
    {
        for (int i=0; i<arr.Length; i++)
        {
            Console.Write($"{arr[i]} ");
        }
        Console.WriteLine($" - {msg}");
    } 
    
    // OUTPUT
    //pink blue red black aqua  - Before method calls
    //aqua black blue pink red  - After orderby inside method
    //pink blue red black aqua  - After method call using orderby
    //aqua black blue pink red  - After sort inside method
    //aqua black blue pink red  - After method call using sort
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   Sweeper    7 年前

    数组是引用类型,因此当您将数组传递给方法时。它的 被路过 .

    您应该知道 arr

    public static void ArrayCalledWithOrderBy(string[] arr)
    {
        arr = (arr.OrderBy(i => i).ToArray()); 
        DisplayArray(arr, "After orderby inside method");
    }
    

    arr公司

    var arr=new string[]{“pink”、“blue”、“red”、“black”、“aqua”};

    ArrayCalledWithOrderBy(arr);

    是两个不同的变量,包含对同一数组的引用,直到此行:

    arr = (arr.OrderBy(i => i).ToArray()); 
    

    arr公司 OrderBy 创建已排序的新数组。原始数组没有变异。

    Array.Sort arr公司

    var arr = new string[] { "pink", "blue", "red", "black", "aqua" };
    
        2
  •  1
  •   Cole Tobin Matt    7 年前

    在这一行中:

    arr = (arr.OrderBy(i => i).ToArray()); 
    

    您正在创建一个新数组并将其分配给 arr arr公司 为了使其他功能可以使用它,您需要使用 ref keyword :

    public static void ArrayCalledWithOrderBy(ref string[] arr)
    
        3
  •  0
  •   jerry    7 年前

    public static void ArrayCalledWithOrderBy(string[] origin)
       {
           var arr = (origin.OrderBy(i => i).ToArray());
           //isEqual flag is false
           var isEqual = Object.ReferenceEquals(arr, origin);
    
          DisplayArray(arr, "After orderby inside method");
       }