为什么GetRange()抛出ArgumentException?

时间:2014-01-16 20:04:38

标签: c#

控制台说:System.argument.exception:偏移量和长度超出数组的范围,或者计数大于从索引到源集合末尾的元素数。

  

在System.Collections.Generic.List 1.GetRange(Int 32 index,Int 32 count) at ConsoleApplication1.Program.sortmerge(List1给出)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {   
        List<int> unsorted = new List<int>();
        Console.WriteLine("Enter the size: ");
        int n=Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the elements of unsorted array: ");
        for (int a = 0; a < n;a++ )
        {
            unsorted.Add(Convert.ToInt32(Console.ReadLine()));


        }
        Console.WriteLine("The elements of your unsorted list are: ");
        foreach (int item in unsorted)
        {
            Console.Write(item.ToString()+"\t");
        }

        List<int> sorted = sortmerge(unsorted); 
        return;
    } //end of main.

    public static List<int> sortmerge(List<int> given)
    {
        if (given.Count == 1)
            return given;

            List<int> sorted = new List<int>();
            int mid = given.Count / 2;
            List<int> arrlft = new List<int>().GetRange(0,mid);
            List<int> arrryt = new List<int>().GetRange(mid,given.Count/2);
           //dividing phase
            arrlft = sortmerge(arrlft);
            arrryt = sortmerge(arrryt);

            //conquering phase
            int leftptr = 0;
            int rightptr = 0;
            for (int i = 0; i < arrryt.Count + arrlft.Count; i++)
            {
                if (leftptr == arrlft.Count)
                {
                    sorted.Add(arrryt[rightptr]);
                    rightptr++;
                }
                else if (rightptr == arrryt.Count)
                {
                    sorted.Add(arrlft[leftptr]);
                }
                else if (arrlft[leftptr] < arrryt[rightptr])
                {
                    sorted.Add(arrlft[leftptr]);
                    leftptr++;
                }
                else
                {
                    sorted.Add(arrryt[rightptr]);
                    rightptr++;
                }
            }   //end of for loop.


            return sorted;


    }


}

}

1 个答案:

答案 0 :(得分:4)

您不希望在新的空GetRange上调用List(这是您在此处所做的new List<int>().GetRange(0, mid)),因为该方法本身从给定实例中提取子集,并且空的任何子集始终为空。

试试这个,

List<int> arrlft = given.GetRange(0, mid);
List<int> arrryt = given.GetRange(mid, given.Count / 2);

您无法在排名为GetRangeindex的空列表中拨打count。来自documentation

  

当index和count不表示List中有效的元素范围时,抛出ArgumentException

此外,如果您阅读了异常消息(您发布了该消息),它会提供问题的线索,

  

System.ArgumentException,偏移量和长度超出数组或计数的范围大于从索引到源集合末尾的元素数。