【问题标题】:how to compare string list and enum list in c# [duplicate]如何在c#中比较字符串列表和枚举列表[重复]
【发布时间】:2021-05-08 14:54:47
【问题描述】:

下面给出了我的用户类

public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string UserName { get; set; }
        public Roles Role { get; set; }
        public List<Role> Roles { get; set; }
    }

下面给出了我的角色类

public class Role
    {
        public int Id { get; set; }
        public string RoleName { get; set; }
    }

我的枚举如下所示

public enum Roles
    {
        Admin,
        Guest,
        Accountant
    }

使用下面给出的代码将字符串与枚举值进行比较时出现错误(无法将字符串与枚举进行比较)

if(User.Roles.Where(m => _roles.Contains(m.RoleName)).ToList()))
    {

    }

=>* 这里 m.RoleName 出现错误(无法将字符串与枚举进行比较)

【问题讨论】:

标签: c# .net linq enums


【解决方案1】:

您可能需要以下两种变体之一:

User.Roles.Where(m => _roles.Any(r => r.ToString().Contains(m.RoleName)))

或者:

User.Roles.Where(m => _roles.Contains((Roles)Enum.Parse(typeof(Roles), m.RoleName)))

【讨论】:

  • 我更喜欢使用泛型解析Enum.Parse&lt;Roles&gt;(m.RoleName)
  • 在if条件下
  • hai @Enigmativity,它不起作用。这是在 if 条件 if(User.Roles.Where(m => _roles.Contains(m.RoleName)).ToList())) { }
  • @Noufal - 你是说你的问题中的代码不起作用?我们已经知道了。你试过我的两个建议了吗?我在发布之前确实测试了这两个。
  • @AlexeyRumyantsev - Enum 的通用解析方法在 4.8 或更早版本中不可用。它肯定在 5.0 中。
【解决方案2】:

你也可以这样比较:

        if (User.Roles.Any(r=> Enum.GetNames(typeof(Roles)).Contains(r.RoleName)))
        {
            Console.WriteLine("Successed");
        }
        else
        {
            Console.WriteLine("UnAuthrize");
        }

【讨论】:

    猜你喜欢
    • 2011-07-28
    • 2021-11-25
    • 2017-07-03
    • 2022-08-24
    • 1970-01-01
    • 2012-04-20
    • 2015-06-22
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多