是否有可能使用LINQ将Enum值与TableData连接

时间:2017-05-27 17:47:35

标签: .net asp.net-mvc

我有一个Enum,我在DB中有一个表,现在要求是显示表数据和连接的枚举。

如何使用LINQ实现。

1 个答案:

答案 0 :(得分:0)

Here is the solution to retrieve the Enum type using the linq with datatable.

namespace StackOverflow_Ex
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable dt = GetEmployeeInfo();

            List<Employee> listName = dt.AsEnumerable().Select(m => new Employee()
            {
                Id = m.Field<int>("EmpId"),
                Name = m.Field<string>("EmpName"),
                EmploymentType = new EmpType { Id =m.Field<int>("EmployeeType"), EmployeeType=  Enum.GetName(typeof(EmployeeType), m.Field<int>("EmployeeType")) }

            }).ToList();


        }

       static DataTable GetEmployeeInfo()
        {

            DataTable dtEmp = new DataTable();
            DataColumn dcId = new DataColumn("EmpId");
            dcId.DataType = typeof(Int32);
            DataColumn dcNm = new DataColumn("EmpName");
            dcNm.DataType = typeof(string);
            DataColumn dcEmpType = new DataColumn("EmployeeType");
            dcEmpType.DataType = typeof(Int32);

            dtEmp.Columns.Add(dcId);
            dtEmp.Columns.Add(dcNm);
            dtEmp.Columns.Add(dcEmpType);

            DataRow dr = dtEmp.NewRow();
            dr["EmpId"] = 1;
            dr["EmpName"] = "Ravi";
            dr["EmployeeType"] = 2;
            dtEmp.Rows.Add(dr);

            return dtEmp;
        }


    }

    public enum EmployeeType
    {
        Permanent = 0,
        Contract = 1,
        PartTime = 2
    }
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public EmpType EmploymentType { get; set; }

    }

    public class EmpType
    {
        public int Id { get; set; }

        public string EmployeeType { get; set; }


    }

}