You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 10:33:16