开发者

Why I am getting Null from this statement. Query Syntax in C#

This is not working. Returns Null to dept_list.

        var dept_list = ((from map in DtMapGuestDepartment.AsEnumerable()
 开发者_Go百科                        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);
}


It's the cast as IEnumerable<DataRow> that is probably failing. If T is not convertible to U, then the expression foo as U will return null for any T foo. It looks like the result of the first LINQ statement (up to the as expression) is actually an IEnumerable<long?>.

The second statement works since you're letting type inference do the work for you.


in the first example you select map.Field>("Department_id")) so its return value is not IEnumerable

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜