【问题标题】:How to convert string into Boolean flags in C# LinQ?如何在 C# LinQ 中将字符串转换为布尔标志?
【发布时间】:2014-10-03 00:09:26
【问题描述】:

我已将布尔标志声明如下。

[Flags]
    public enum StudentStatus
    {
        True = 1,
        False = 2

    }

我正在通过下一行中的 DataValues 集合获取值,我想将它分配到下面的属性中。

var student= new Student();

student.Status= StudentInfo.Data.DataValues
                .Where(m => m.FieldName.Equals("Status"))
                .Select(m => m.StatusValue).SingleOrDefault();

【问题讨论】:

    标签: linq asp.net-mvc-4 c#-4.0 linq-to-sql


    【解决方案1】:

    由于您使用的是 .Net Framework 4,因此您可以使用 Enum.TryParse 方法。

    var student= new Student();
    
    string status = StudentInfo.Data.DataValues
                                     .Where(m => m.FieldName.Equals("Status"))
                                     .Select(m => m.StatusValue).SingleOrDefault();
    StudentStatus studentStatus;
    Enum.TryParse(status, out studentStatus);
    
    student.Status = studentStatus;
    

    如果解析操作失败,结果包含StudentStatus的默认值。

    【讨论】:

      【解决方案2】:

      首先,该枚举不太适合作为[Flags] 枚举。 [Flags] 仅在可以同时激活多个不同值时使用。它应该声明为:

      // Removed [Flags] - not appropriate here.
      public enum StudentStatus
      {
          True = 1,
          False = 2
      }
      

      在任何情况下,您都可以使用Enum.Parse 将字符串解析回枚举。像这样:

      string statusString = StudentInfo.Data.DataValues
                                       .Where(m => m.FieldName.Equals("Status"))
                                       .Select(m => m.StatusValue).SingleOrDefault();
      
      student.Status = (StudentStatus) Enum.Parse(typeof(StudentStatus), statusString);
      

      这适用于[Flags] 和普通枚举。

      【讨论】:

      • 非常感谢您的快速回复。有一种方法需要设置标志。上面的例子是为了理解这种场景下的转换。那么您的代码是否可以正常工作,包括标志?
      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 2011-02-17
      • 2012-04-02
      • 2021-02-23
      • 2010-09-20
      • 2016-11-27
      相关资源
      最近更新 更多