Shantanu Gupta
Shantanu Gupta

Reputation: 21198

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()
                         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. ?

Upvotes: 0

Views: 510

Answers (3)

Heinzi
Heinzi

Reputation: 172270

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);
}

Upvotes: 3

Itay Karo
Itay Karo

Reputation: 18286

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

Upvotes: 0

Chris Schmich
Chris Schmich

Reputation: 29476

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.

Upvotes: 1

Related Questions