是否有可能通过其位置值迭代像数组一样的枚举?

时间:2015-04-10 20:08:32

标签: c# enums

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

    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的“位置值”,那么这将很好地插入到数组counter.TimePeriodCount[]中。但我还没有找到如何做到这一点。

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

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

或者我只是以错误的方式接近这个?

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

Update2 现在我了解应该使用AlexD解决方案的方式,这也是解决问题的一种非常好的方法。感谢。

2 个答案:

答案 0 :(得分:5)

您可以使用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;
}

BTW,同样Enum.GetNames会给你这些名字。

答案 1 :(得分:1)

你应该能够做到这一点

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