I'm trying to merge the results from two tables in to a list and then display it in a dictionary where the key is the domain and the value is a list of urls from both tables.
class Source1Entity { string Domain {get;} string PageUrl {get;} /* more properties */ }
class Source2Entity { string Domain {get;} string PageUrl {get;} /* more properties */ }
I've got this far:
Dictionary<string, List<string>> results =
from firstSource in context.Source1
join secondSource in context.Source2 on firstSource.Domain equals secondSource.Domain
group firstSource by firstSource.Domain into g
...
It's not entirely clear, but I suspect you actually want to treat these two tables as equivalents - so you can project to a common form and then use Concat
, then call ToLookup
:
var projectedSource1 = context.Source1.Select(x => new { x.Domain, x.PageUrl });
var projectedSource2 = context.Source2.Select(x => new { x.Domain, x.PageUrl });
var results = projectedSource1
.Concat(projectedSource2)
.ToLookup(x => x.Domain, x => x.PageUrl);
Then:
// For a particular domain - you'll get an empty sequence it the
// domain isn't represented
foreach (var url in results[domain])
or
foreach (var entry in results)
{
Console.WriteLine("Domain: {0}", entry.Key);
foreach (var url in entry)
{
Console.WriteLine(" Url: {0}", url);
}
}
While you could use a Dictionary
for this, a Lookup
is generally more suitable for single-key-multiple-value queries.
See more on this question at Stackoverflow