从月份数组中获取一系列值
本文关键字:获取 一系列 数组 | 更新日期: 2023-09-27 18:13:00
我创建了一个数组[Framework version 2.0, c# 2.0]来存储一年中的月份,如下所示
来源public readonly static string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
我正在寻找一种方法来检索从这个静态列表返回range of months
的IEnumerable
。我可以想到很多方法,但我在这里找到一个让我去wahhhhhh…方法的签名看起来像
public IEnumerable<String> GetRange(int startIndex,int endIndex);
样本I/O
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.
如果你想使用Array。复制,你可以这样做:
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;
}
我要感谢每一个花心思回答我问题的人- 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];
}
}
我想知道我是否可以在范围内使用fetch方法从索引方法中获取。
您可以使用Skip和Take扩展方法:
public IEnumerable<String> GetRange(int startIndex, int endIndex)
{
return months.Skip(startIndex).Take(endIndex - startIndex + 1);
}
(可能需要为基于1的索引进行调整)
下面的内容适合您吗?
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;
}