如何为List<CategoriesDto>补充CategoriesEnum中所有缺失的枚举项?
解决方案
实现思路
- 获取
CategoriesEnum的全部枚举值 - 对比现有列表,筛选出未包含的枚举项
- 为缺失项创建
CategoriesDto实例(利用类中Enabled的默认值false)并添加到列表
代码实现
using System; using System.Collections.Generic; using System.Linq; public static class CategoriesListExtensions { public static List<CategoriesDto> EnsureAllCategories(this List<CategoriesDto> categoriesList) { // 获取枚举的所有取值 var allCategoryEnums = Enum.GetValues<CategoriesEnum>(); // 用HashSet存储已存在的分类,提升查找效率 var existingCategories = categoriesList.Select(dto => dto.Name).ToHashSet(); foreach (var category in allCategoryEnums) { if (!existingCategories.Contains(category)) { // 缺失的分类直接用默认构造,Enabled已默认设为false categoriesList.Add(new CategoriesDto { Name = category }); } } return categoriesList; } }
使用示例
针对你给出的案例场景,调用方法即可自动补充缺失项:
var categoriesList = new List<CategoriesDto> { new() { Name = CategoriesEnum.TV, Enabled = true, }, new() { Name = CategoriesEnum.AC, Enabled = true, } }; // 执行补全逻辑 categoriesList.EnsureAllCategories(); // 处理后列表包含TV、AC、Car、Fridge,其中Car和Fridge的Enabled为默认false
兼容说明
如果使用.NET Framework或.NET 5以下版本,将Enum.GetValues<CategoriesEnum>()替换为:
var allCategoryEnums = (CategoriesEnum[])Enum.GetValues(typeof(CategoriesEnum));
可选优化
如果需要让列表按枚举定义的顺序排列,可以在补全后添加排序逻辑:
categoriesList.Sort((a, b) => a.Name.CompareTo(b.Name));
内容的提问来源于stack exchange,提问作者Saurabh Soni
相关产品推荐
相关产品推荐

