如何简洁地将int列表转换为enum列表及反向转换?
简化List与List的互转方法
正向转换(List → List)
你原来的循环写法可以用LINQ大幅简化,同时保留空值处理和过滤0值的逻辑:
public List<AutoShipOption> AutoShipOptionsMapper(List<int> values) { // 处理null输入,过滤掉0值并转换枚举类型 return values?.Where(v => v > 0) .Select(v => (AutoShipOption)v) .ToList() ?? new List<AutoShipOption>(); }
如果需要验证输入的int是否为合法枚举值(避免无效数值被强制转换),可以加上Enum.IsDefined校验:
public List<AutoShipOption> AutoShipOptionsMapper(List<int> values) { return values?.Where(v => Enum.IsDefined(typeof(AutoShipOption), v) && v > 0) .Select(v => (AutoShipOption)v) .ToList() ?? new List<AutoShipOption>(); }
反向转换(List → List)
同样用LINQ实现简洁的反向转换:
public List<int> AutoShipOptionsToInts(List<AutoShipOption> options) { return options?.Select(o => (int)o).ToList() ?? new List<int>(); }
说明
values?.是空条件运算符,避免values为null时触发空引用异常?? new List<...>是空合并运算符,当输入为null时直接返回空列表- LINQ的
Where+Select+ToList把循环逻辑浓缩成链式调用,代码更简洁易读
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

