Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of two List with different types using LINQ

Tags:

linq

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.

like image 987
TalkingCode Avatar asked Sep 30 '10 11:09

TalkingCode


3 Answers

You could try something like this.

var missingvehicles = from uV in unsoldVehicles
                    where !listDetailUrls.Contains(uV.UrlID )
                    select uV;
like image 85
kjn Avatar answered Oct 18 '22 12:10

kjn


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();
like image 20
Ani Avatar answered Oct 18 '22 13:10

Ani


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();
like image 27
Yakimych Avatar answered Oct 18 '22 14:10

Yakimych