gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
c#中,如何获取一个枚举对象中,值在指定范围内的枚举列表?
- User
c#中,如何获取一个枚举对象中,值在指定范围内的枚举列表?
- Assistant
在C#中,你可以通过以下方式来获取枚举类型中值在指定范围内的枚举列表。假设你有一个枚举类型,你可以使用
Enum.GetValues方法结合LINQ查询来实现这一点。以下是一个示例代码:csharpusing System; using System.Collections.Generic; using System.Linq; public enum MyEnum { Value1 = 1, Value2 = 2, Value3 = 3, Value4 = 4, Value5 = 5 } class Program { static void Main() { var result = GetEnumValuesInRange<MyEnum>(2, 4); foreach (var item in result) { Console.WriteLine(item); } } static List<T> GetEnumValuesInRange<T>(int minValue, int maxValue) where T : Enum { return Enum.GetValues(typeof(T)) .Cast<T>() .Where(e => Convert.ToInt32(e) >= minValue && Convert.ToInt32(e) <= maxValue) .ToList(); } }