是否可以通过位置值像数组一样遍历枚举?

Is it possible to iterate through enums like an array by its position value?

有没有办法遍历枚举或检索它在枚举列表中的位置。我有以下示例代码。

    private static void Main(string[] args)
    {
        DateTime sinceDateTime;
        Counters counter = new Counters();

        // Iterate through time periods
        foreach (TimePeriodsToTest testTimePeriod in Enum.GetValues(typeof(TimePeriodsToTest)))
        {
            // e.g. DateTime lastYear = DateTime.Now.AddDays(-365);
            sinceDateTime = DateTime.Now.AddDays((double)testTimePeriod);
            var fileCount =
                Directory.EnumerateFiles("c:\Temp\")
                    .Count(path => File.GetCreationTime(path).Date > sinceDateTime);

            Console.WriteLine("Files since " + -(double)testTimePeriod + " days ago is : " + fileCount);
            // counter.TimePeriodCount[testTimePeriod] = fileCount;
        }
    }

    public enum TimePeriodsToTest
    {
        LastDay = -1,
        LastWeek = -7,
        LastMonth = -28,
        LastYear = -365
    }

    public class Counters
    {
        public int[] TimePeriodCount = new int[4];
    }

    public class Counters2
    {
        public int LastDay;
        public int LastWeek;
        public int LastMonth;
        public int LastYear;
    }

所以我想将值 fileCount 存储到 counter.TimePeriodCount[] 中。如果我能得到 testTimePeriod 的 'position value',那么它会很好地插入数组 counter.TimePeriodCount[]。但我还没有找到如何做到这一点。

如果 LastDay、LastWeek 等是 1、2、3、4 那么这不是问题,但它们不是,我有问题!

或者,是否有办法在后续迭代中将 fileCount 存储到 Counters2.LastDayCounters2.LastWeek 等中?

或者我只是用错误的方式来解决这个问题?

更新 "KuramaYoko" 给出的建议可以通过在解决方案中添加字典来实现,但我发现 Jones6 给出的解决方案更加优雅,因为它不需要添加字典。感谢您花费时间和精力,因为我从这两个答案中学到了一些东西:-)

Update2 现在我明白了AlexD解决方案的使用方法,那也是一个很好的解决问题的方法。谢谢。

您可以使用Enum.GetValues 方法获取所有枚举值。我怀疑顺序是否有保证,所以你可能想对值进行排序。

int[] values = Enum.GetValues(typeof(TimePeriodsToTest))
    .Cast<int>()
    .OrderBy(x => x)
    .ToArray();

for (int k = 0; k < values.Length; k++)
{
    sinceDateTime = DateTime.Now.AddDays(values[k]);
    fileCount = ....
    counter.TimePeriodCount[k] = fileCount;
}

顺便说一句,同样 Enum.GetNames 会给你名字。

你应该可以做到这一点

foreach (var testTimePeriod in Enum.GetValues(typeof(TimePeriodsToTest)).Cast<TimePeriodsToTest>().Select((x, i) => new { Period = x, Index = i}))
{
     counter.TimePeriodCount[testTimePeriod.Index] = fileCount;
}