Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Left Outer Join lambda expression error

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?

like image 807
rafilho Avatar asked May 20 '26 00:05

rafilho


1 Answers

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

like image 192
Jon Skeet Avatar answered May 22 '26 19:05

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!