我创建了一个数组[Framework version 2.0,C#2.0],它存储了一年中的月份
public readonly static string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
我正在寻找一种方法来检索从此静态列表中返回IEnumerable
的{{1}}。我可以想到很多方法,但我在这里找到一个让我走的哇哇......
方法的签名看起来像
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
答案 0 :(得分:1)
如果你想使用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
答案 1 :(得分:1)
我要感谢每一个愿意回答我的问题的人 - 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方法 从索引方法中获取。
答案 2 :(得分:0)
您可以使用Skip and Take Extension方法:
public IEnumerable<String> GetRange(int startIndex, int endIndex)
{
return months.Skip(startIndex).Take(endIndex - startIndex + 1);
}
(可能需要针对基于1的指数进行调整)
答案 3 :(得分:0)
以下内容适用于您?
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;
}