Получение диапазона значений из массива месяцев - PullRequest
0 голосов
/ 02 ноября 2011

Я создал массив [Framework версия 2.0, C # 2.0], в котором хранятся месяцы года примерно так:

source

public readonly static string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

Я ищу способ получения IEnumerable который возвращает range of months из этого статического списка.Я могу придумать много способов, но я здесь, чтобы найти тот, который заставляет меня идти вахххххх ... подпись метода будет выглядеть примерно так:

подпись

public IEnumerable<String> GetRange(int startIndex,int endIndex);

пример ввода / вывода

startindex = 1
endindex = 10
returns months from January ,February,March upto October

примечание: Array.Copy аккуратен, но способ использования параметров делает его странным

Parameters

sourceArray

    The Array that contains the data to copy.

sourceIndex

    A 32-bit integer that represents the index in the sourceArray at which copying begins.

destinationArray

    The Array that receives the data.

destinationIndex

    A 32-bit integer that represents the index in the destinationArray at which storing begins.

length

    A 32-bit integer that represents the number of elements to copy.

Ответы [ 4 ]

1 голос
/ 02 ноября 2011

Я хотел бы поблагодарить каждого человека, который решил ответить на мой вопрос - Thanks вот код, который работал для меня, используя объекты Inhouse

Выборки в диапазоне

public static IEnumerable<string> GetRange(short startIndex, short endIndex)
    {
        /*Cases
         * end > start
         * end > bounds
         * start < bounds
         * start != end
         */
        if (startIndex > endIndex || endIndex > Months.Length || startIndex < 0 || startIndex == endIndex)
        {
            throw new ArgumentOutOfRangeException("startIndex", "Invalid arguments were supplied for Start and End Index");
        }
        for (int rangeCount = startIndex-1; rangeCount < endIndex; rangeCount++)
        {
            yield return Months[rangeCount];
        }
    }

Извлекает данные из указанного индекса до конца

public static IEnumerable<string> GetFrom(int startIndex)
{
    if (startIndex < 0 || startIndex > Months.Length - 1)
    {
        throw new ArgumentOutOfRangeException("startIndex", "Start Index cannot be greater than the Bounds of the months in year");
    }

    for (int rangeCount = startIndex - 1; rangeCount < Months.Length; rangeCount++)
    {
        yield return Months[rangeCount];
    }
}

Я хотел бы знать, могу ли я использовать выборку внутри метода диапазона внутри выборки из метода индекса.

1 голос
/ 02 ноября 2011

Если вы хотите использовать Array.Copy, вы можете сделать это следующим образом:

public IEnumerable<String> GetRange(int startIndex, int endIndex)
{
    int numToCopy = endIndex - startIndex + 1;
    string[] result = new string[numToCopy];
    Array.Copy(Months, startIndex - 1, result, 0, numToCopy); // startIndex - 1 because Array indexes are 0-based, and you want the first element to be indexed with 1
    return result;
}

Это работает с .NET 2.0

0 голосов
/ 02 ноября 2011

Хотелось бы что-нибудь для вас?

    public static IEnumerable<String> GetRange(int startIndex, int endIndex)
    {
        List<string> rv = new List<string>();
        for (int i=startIndex+1;i<=endIndex;i++)
            rv.Add(System.Globalization.DateTimeFormatInfo.CurrentInfo.GetMonthName(i));
        return rv;
    }
0 голосов
/ 02 ноября 2011

Вы можете использовать методы пропуска и расширения:

public IEnumerable<String> GetRange(int startIndex, int endIndex)
{
    return months.Skip(startIndex).Take(endIndex - startIndex + 1);
}

(может потребоваться корректировка для индексов на основе 1)

...