I’m pretty sure this falls under a “UNION” scenario but I’m really just looking for the best approach to solve my problem (even if it’s not a UNION).
I have a query that looks like this:
var query = context.AffiliateConfigurations.Where(x => x.AffiliateId == affiliateId).Select(config => new ViewModels.ConfigurationItem
{
ConfigurationId = config.AffiliateConfigurationId,
ConfigKey = config.ConfigKey,
ConfigValue = config.ConfigValue,
UpdatedDate = config.UpdatedDate,
ConfigurationType = ViewModels.ConfigurationType.Affiliate
});
What I want to do is add some more results to that query. I have another table called SiteConfiguration that has the EXACT same schema but I want to add only rows from that table where the ConfigKey does not already exist in my original query.
I have something like the following currently (and it works), but I’m looking for a “pure” LINQ way to do it:
var items = context.AffiliateConfigurations.Where(x => x.AffiliateId == affiliateId).Select(config => new ViewModels.ConfigurationItem
{
ConfigurationId = config.AffiliateConfigurationId,
ConfigKey = config.ConfigKey,
ConfigValue = config.ConfigValue,
UpdatedDate = config.UpdatedDate,
ConfigurationType = ViewModels.ConfigurationType.Affiliate
}).ToList();
var query = context.SiteConfigurations.Select(config => new ViewModels.ConfigurationItem
{
ConfigurationId = config.SiteConfigurationId,
ConfigKey = config.ConfigKey,
ConfigValue = config.ConfigValue,
UpdatedDate = config.UpdatedDate
});
foreach (var item in query)
{
if (items.All(x => x.ConfigKey != item.ConfigKey))
{
items.Add(item);
}
}
So your Question is
"I have two collections and i want to merge them.how do i exclude items from the second collection,if the item's property is matching with another item's property on the first list."Yes LINQ’s UNION is what you need in such scenarios
All you need to do is a Write a simple Comparer class(Implementing the IEqualityComparer interface)for your
ConfigurationItemThat is all you need.You can now run the UNION query and get your expected output.