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

如何检测列表中Type/AccessType/Value一致但Action不同的Privilege并抛异常

检查Privilege列表中的冲突实例并抛出异常

嘿,这个需求很明确——咱们要确保列表里不会出现Type、AccessType、Value完全一致,但Action不同的Privilege实例,一旦发现就抛出异常。下面我用C#给你写个具体的实现方案,思路清晰又好维护:

1. 先定义Privilege类

首先咱们先把基础的Privilege类写出来(和你例子里的结构一致):

public class Privilege
{
    public string Type { get; set; }
    public string AccessType { get; set; }
    public string Value { get; set; }
    public string Action { get; set; }
}

2. 实现冲突检查逻辑

我推荐用LINQ的分组功能来做这个检查,代码简洁还能清晰定位冲突的分组:

using System.Linq;

public static class PrivilegeValidator
{
    public static void ValidateNoConflictingPrivileges(List<Privilege> privileges)
    {
        // 按Type、AccessType、Value分组,检查每组的Action是否有多种不同值
        var conflictingGroups = privileges
            .GroupBy(p => new { p.Type, p.AccessType, p.Value })
            .Where(g => g.Select(p => p.Action).Distinct().Count() > 1);

        if (conflictingGroups.Any())
        {
            // 把冲突的组信息整理到异常消息里,方便调试
            var conflictDetails = string.Join(Environment.NewLine, 
                conflictingGroups.Select(g => 
                    $"冲突项: Type={g.Key.Type}, AccessType={g.Key.AccessType}, Value={g.Key.Value} " +
                    $"对应的Action有: {string.Join(", ", g.Select(p => p.Action).Distinct())}"));
            
            throw new InvalidOperationException("发现冲突的Privilege实例:" + Environment.NewLine + conflictDetails);
            // 如果你想更精准,也可以自定义一个异常类,比如PrivilegeConflictException
        }
    }
}

3. 测试示例

咱们来验证一下这个逻辑:

// 测试冲突场景
var conflictingPrivileges = new List<Privilege>
{
    new Privilege { Type = "a", AccessType = "a", Value = "a", Action = "a" },
    new Privilege { Type = "a", AccessType = "a", Value = "a", Action = "b" },
    new Privilege { Type = "b", AccessType = "b", Value = "b", Action = "c" }
};

try
{
    PrivilegeValidator.ValidateNoConflictingPrivileges(conflictingPrivileges);
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Message);
    // 输出会显示具体的冲突信息,方便排查
}

// 测试正常场景
var validPrivileges = new List<Privilege>
{
    new Privilege { Type = "a", AccessType = "a", Value = "a", Action = "a" },
    new Privilege { Type = "b", AccessType = "b", Value = "b", Action = "c" }
};

PrivilegeValidator.ValidateNoConflictingPrivileges(validPrivileges);
// 这里不会抛出异常,正常执行

补充说明

  • 如果你觉得InvalidOperationException不够贴合业务,可以自定义一个PrivilegeConflictException类,让异常语义更明确。
  • 这个逻辑的时间复杂度主要由分组操作决定,对于大多数业务场景来说完全够用;如果是超大规模的列表,可以考虑提前用字典做缓存优化,但一般没必要。

内容的提问来源于stack exchange,提问作者fota666

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:36:05