Mahesh Waghmare Mahesh Waghmare -4 years ago 333
C# Question

Convert DataTable to Dictionary with enum as column C#

There is one Enum viz. CarEnum having values
All - 1
BMW - 2
Audi - 3

I am getting this DataTable from database

DataTable dt = new DataTable();
dt.Columns.Add("ID", long);
dt.Columns.Add("EnumID", Int16);


I want to convert this table into
Dictionary
with
EnumID
as
Enum


Dictionary format

Dictionary<long, CarEnum> _Record = new Dictionary<long, CarEnum>();


I have tries below codes but they are not

_Record = dt.AsEnumerable().ToDictionary<DataRow, long, CarEnum>(row => row.Field<long>("ID"), row => (CarEnum)Enum.ToObject(typeof(CarEnum), row.Field<Int16>("EnumID")));
_Record = dt.AsEnumerable().ToDictionary<DataRow, long, CarEnum>(row => row.Field<long>("ID"), row => (CarEnum)(int)row.Field<Int16>("EnumID"));


both codes are not working and got exception specific cast in not valid.

Please help.

Answer Source

From my understanding you can cast only specific primitive to enum.

Please see this link to MSDN.

Use short instead of Int16 or cast Int16 to short before casting to enum.

Edit: Maybe you trying to cast a zero value and it is not defined in your enum ?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download