KyloRen KyloRen - 12 days ago 8
C# Question

Why are these two LINQ queries different? When they seem to be the same

I would like know why these two LINQ queries are different, or why one works and the other does not? Obviously the compiler says they are different, but I can't seem to find out why?

I want the first query to work, but no matter what I do It won't work.

The below LINQ query gives me an error of,


Cannot implicitly convert type 'int?' to
'System.Collections.Generic.IEnumerable'


public static IEnumerable<int?> GetTenantFacilityCosts(int? code, DateTime date, int number)
{
return DataContext.Facility_Cost_TBLs.
Where(p => p.Tenant_Code == code &&
p.Code_Date == number &&
p.Date_Year == date.Year &&
p.Date_Month == date.Month).
FirstOrDefault().Tenant_Portion;
}


But this query below gets the
int
value that I am trying to get and does not throw an error.

int? facilityCost =
DataContext.Facility_Cost_TBLs.
Where(p => p.Tenant_Code == selectedTenant.Tenant_Code &&
p.Code_Date == 10 &&
p.Date_Year == date.Year &&
p.Date_Month == date.Month).
FirstOrDefault().Tenant_Portion;


Why are these two queries differnt and how would I get the first one to work correctly?

Answer

The Linq query returns a nullable int i.e. int?, the reason it works for the second is because it is assigning the value to a int?.

The second one is returning a int? on a method that is trying to return: IEnumerable<int?>. If you want to return an enumerable of the results you need to remove the FirstOrDefault from the query. And judging by the method name, i.e. the plural Costs, this is what you want.

However if you only want one result change the method signature to:

public static int? GetTenantFacilityCosts(int? code, DateTime date, int number)