This is not working. Returns Null to dept_list.
var dept_list = ((from map in DtMapGuestDepartment.AsEnumerable()
where map.Field<Nullable<long>>("Guest_Id") == 174
select map.Field<Nullable<long>>("Department_id")).Distinct())as IEnumerable<DataRow>;
DataTable dt = dept_list.CopyToDataTable(); //dept_list comes null here
This works as desired.
var dept_list = from map in DtMapGuestDepartment.AsEnumerable()
where map.Field<Nullable<long>>("Guest_Id") == 174
select map;
DataTable dt = dept_list.CopyToDataTable(); //when used like this runs correct.
What mistake is being done by me here. ?
Your first query is returning an enumerable of values (of the department IDs) instead of an enumerable of data rows (as in the second query).
Since IEnumerable<Nullable<long>>
is not a subtype of IEnumerable<DataRow>
, the as
operator returns null.
(As a side note, using a normal cast instead of as
would have given you an InvalidCastException
, which is more helpful in finding errors than just returning null
.)
EDIT: If you really need a DataTable in the end, I guess you will have to construct it manually (untested):
var dept_list = ((from map in DtMapGuestDepartment.AsEnumerable()
where map.Field<Nullable<long>>("Guest_Id") == 174
select map.Field<Nullable<long>>("Department_id")).Distinct())
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Department_id", typeof(long?)));
foreach (long? dept in dept_list) {
dt.Rows.Add(dept);
}