Linq custom union for objects

I need to concatenate these strings on two IDs without using IEqualityComparer

as they are not supported in LINQ to Entities.

Q result

I need each unique combination BizId

and BazId

with a value from foos

if the id pair came from there, otherwise the value must be zero. This is a very simplified example, and in fact these tables are very large and these operations cannot be performed in memory. Because of this, this query must work with LINQ to Entities so that it can be translated into valid SQL and executed against the database. I suspect that this can be done with a certain combination where

, join

and DefaultIfEmpty()

instead of Union

and Distinct()

, but for now I'm at a loss.

var foos = from f in Context.Foos where f.isActive select new { BizId = f.bizId, BazId = f.BazId, Value = f.Value };
var bars = from b in Context.Bars where b.isEnabled select new { BizId = b.bizId, BazId = b.BazId, Value = 0 };
var result = foos.Union(bars).Distinct(); //I need this to compare only BizId and BazId

      

+3


source to share


1 answer


You can group by two fields and then get the first element of each group:



foos.Union(bars).GroupBy(x => new { x.bizId, x.bazId })
    .Select(g => g.FirstOrDefault())

      

+1


source







All Articles