I have the following tables:
Table1
{
Code //string
Desc //string
}
Table2
{
Code //string
Value //decimal?
}
I need to Left Join the tables and for each Table2 Code/Value missing I want to show Code = Table1.Code, Desc = Table1.Desc and Value = null or blank.
I tryied the following lambda expression:
var result = Table1.GroupJoin(
Table2,
x => x.Code,
y => y.Code,
(x, y) => g
.Select(c => new { x.Code, x.Desc, Value = y.Value })
.DefaultIfEmpty(new { x.Code, x.Desc, Value = null }))
.SelectMany(g => g);
and got these errors:
The type arguments for method 'System.Linq.Enumerable.DefaultIfEmpty(System.Collections.Generic.IEnumerable, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Cannot assign to anonymous type property
So, I changed ...DefaultIfEmpty... Value = 0 }...
and got these errors: 'System.Collections.Generic.IEnumerable' does not contain a definition for 'DefaultIfEmpty' and the best extension method overload 'System.Linq.Queryable.DefaultIfEmpty(System.Linq.IQueryable, TSource)' has some invalid arguments
Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Linq.IQueryable'
Any idea to solve the errors?
You just need to specify the type of the null
value in your anonymous type initializer:
.DefaultIfEmpty(new { x.Code, x.Desc, Value = (decimal?) null }))
When you used 0, you were creating a separate anonymous type that had a Value
property of type int
, instead of decimal?
.
See more on this question at Stackoverflow