I am trying the get the different of two lists with a LINQ query. But the lists are not of the same type.
List<Vehicle> unsoldVehicles
List<string> ListDetailUrls
Each Vehicle Object has a field called UrlID (string) while the ListDetailUrls list consists only of strings. I need every Vehicle from the Vehicle List where the field UrlID does not match an entry ListDetailUrls.
What I have done so far is :
List<Vehicle> missingVehicles = new List<Vehicle>(
from uV in unsoldVehicles
from de in ListDetailUrls
where uV.UrlID != de
select uV);
But with a query like this my missingVehicles are more items than the unsoldVehicles!
I was looking for a way to use the Except-method somehow but I only find samples where both lists are of the same type.
You could try something like this.
var missingvehicles = from uV in unsoldVehicles
where !listDetailUrls.Contains(uV.UrlID )
select uV;
The reason your current query is incorrect is because all combinations of (vehicle, url)
where vehicle.UrlID ! = url
will make it past the filter., whereas what you really want to do is to prevent a vehicle from being included if any url in the list matches its UrlId
.
Not only will your query return the vehicles that should be filtered out, but each vehicle will be repeated multiple times.
I suggest:
var urlIds = new HashSet<string>(ListDetailUrls);
var missingVehicles = unsoldVehicles.Where(vehicle => !urlIds.Contains(vehicle.UrlID))
.ToList();
If I understand correctly, you need all the items from the unsoldVehicles
list with UrlIDs
that don't appear in the ListDetailUrls
list:
var missingVehicles = unsoldVehicles.Where(uv => !ListDetailUrls.Contains(uv.UrlID)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With