【问题标题】:Generic List<Type> to enum通用列表<Type> 到枚举
【发布时间】:2013-11-27 13:16:39
【问题描述】:

我有以下课程

public partial class ActionType
{
    public System.Guid ActionTypeId { get; set; }
    public string ActionTypeName { get; set; }
}

现在我想像这样使用存储在数据库中的所有 ActionType:

MyEntity entity = new MyEntity();
entity.ActionTypeId = ActionTypes.??? 

在这里我希望能够通过 ActionTypeName 选择 ActionTypeId。

现在我是这样做的:

public class ActionTypes
{
    public static readonly Guid CustomerAdded = new Guid("36520b53-e1d0-4c96-bec8-0df85536a96b");
    public static readonly Guid CustomerEdited = new Guid("732592d3-7423-4250-aa74-e10fe1e7c030");
}

我希望能够以编程方式从数据库中创建 ActionTypes,而不是自己编写值。

所以我想做这样的事情:

public class ActionTypes
{
   List<ActionType> list = context.GetAllActionTypes();
   foreach(ActionType type in list)
   {
      public static readony Guid type.ActionTypeName = type.ActionTypeId;
   }
}

如何实现我的意图?

最好的问候

【问题讨论】:

  • 我不确定我是否理解。 Dictionary&lt;string, Guid&gt; 有帮助吗?
  • 你在这里问什么非常不清楚。您拥有的代码有效,您想要什么不同?
  • 对不起,我已经编辑了问题

标签: c# list enums


【解决方案1】:

也许你需要一个字典(查找表、地图)?

public class ActionTypes
{
   private List<ActionType> list = context.GetAllActionTypes();
   private Dictionary<string, Guid> ActionTypesMap { get; private set; }

   public ActionTypes() {
     this.ActionTypesMap = list.ToDictionary(
       k => k.ActionTypeName,
       v => v.ActionTypeId);
   }
}

访问为:Guid addedGuid = new ActionTypes().ActionTypesMap ["CustomerAdded "]

【讨论】:

  • 我可以通过以下方式达到同样的效果:Guid addedGuid = list.FirstOrDefault(x=>x.ActionTypeName == "CustomerAdded").ActionTypeId;
  • 那你想如何引用你的动作类型呢?你需要以某种方式知道这个名字。我知道您可以使用 FirstOrDefault 来做到这一点(字典更快,但使用更多内存)。
【解决方案2】:

您可以使用 T4 模板在编译时生成文件。这具有保持智能感知和验证成员名称的额外好处。

类似这样的:

ActionTypes.tt:

<#@ template   language    = "C#"                           #>
<#@ assembly   name        = "Microsoft.CSharp"             #>
<#@ assembly   name        = "System.Core"                  #>
<#@ assembly   name        = "System.Data"                  #>
<#@ import     namespace   = "System.Collections.Generic"   #>
<#@ import     namespace   = "System.Dynamic"               #>
<#@ import     namespace   = "System.Linq"                  #>
<#@ import     namespace   = "System.Data.SqlClient"        #>

public class ActionTypes 
{
<#
var con = new SqlConnection("Data Source=localhost\SQLExpress;Initial Catalog=MyDatabaseName;Integrated Security=True");
con.Open();

var sqc = new SqlCommand("SELECT ActionTypeID, ActionTypeName FROM ActionTypes", con);
var reader = sqc.ExecuteReader();

using (var reader = sqc.ExecuteReader())
{
    while (reader.Read())
    {
#>
    public static Guid <#=reader.GetString(reader.GetOrdinal("ActionTypeName"))#> = new Guid("<#=reader.GetGuid(reader.GetOrdinal("ActionTypeID"))#>");
<#
    }
}
con.Close();
#>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多